package com.jinzhi.jzweb.controller;


import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import static java.lang.Math.abs;
import java.time.Year;
import java.util.*;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinzhi.api.util.JWTUtil;
import com.jinzhi.common.config.Constant;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.examination.pojo.ExaminationsPercentVo;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.*;
import com.jinzhi.jzweb.pojo.bo.ProvinceCostStandardBO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.ExaminationCostAnalysisUtil;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.RoleDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.mysql.jdbc.StringUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

/**
 *
 * <pre>
 *
 * </pre>
 * <small> 2021-04-19 09:36:13 | Long</small>
 */
@Controller
@RequestMapping("/jzweb/examinationCost")
public class ExaminationCostController extends BaseController {
	@Autowired
	private ExaminationCostService examinationCostService;
	@Autowired
	private CertificationBatchService certificationBatchService;
	@Autowired
	private ExaminationBatchService examinationBatchService;
	@Autowired
	private StuSignUpService stuSignUpService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private BookOrderService bookOrderService;
	@Autowired
	private ArchivesService archivesService;

	@Autowired
	private RegionService regionService;

	@Autowired
	private RefundMoneyLogService refundMoneyLogService;



	@GetMapping()
	@RequiresPermissions("jzweb:examinationCost:examinationCost")
	String ExaminationCost(Integer year,Model model){
	    model.addAttribute("year",year);
		return "jzweb/examinationCost/examinationCost";
	}






//	/**
//	 *
//	 * @param type 0 = 查询省 1 = 查询市
//	 * @return
//	 */
//	@ResponseBody
//	@GetMapping("/userProvinceSel")
//	public Result<?> userProvinceSel(String type,String name){
//		UserDO user = getUser();
//
//		List<String> ids =new ArrayList<>();
//		if (type.equals("0")) { //省
//			ids	= splitStrArrayList(user.getRegionProvinceId());
//			if ((user.getRegionProvinceId() == null||"".equals(user.getRegionProvinceId())) && (user.getRegionCityId() == null||"".equals(user.getRegionCityId()))){  //如果没配置任何权限就查询全部省
//				Wrapper<RegionDO> wrapper = new EntityWrapper<RegionDO>();
//				wrapper.eq("parent_id","0");
//				if(name !=null && !name.equals("")){
//					wrapper.like("name",name);
//				}
//				return Result.ok(regionService.selectList(wrapper));
//			}else {
//				List<RegionDO> regionDOList = regionService.selectBatchIds(ids);
//				if(name !=null && !name.equals("")){
//					regionDOList = regionDOList.stream().filter(r -> r.getName().contains(name)).collect(Collectors.toList());
//				}
//				return Result.ok(regionDOList); //最终结果
//			}
//		}else if (type.equals("1")){ //城市
//			if ((user.getRegionProvinceId() == null||"".equals(user.getRegionProvinceId())) && (user.getRegionCityId() == null||"".equals(user.getRegionCityId()))){  //如果没配置任何权限就查询全部城市
//				Wrapper<RegionDO> wrapper = new EntityWrapper<RegionDO>();
//				wrapper.ne("parent_id","0");
//				if(name !=null && !name.equals("")){
//					wrapper.like("name",name);
//				}
//				return Result.ok(regionService.selectList(wrapper));
//			}else {
//				ids = splitStrArrayList(user.getRegionCityId()); //获取城市id
//				Wrapper<RegionDO> idWrapper = new EntityWrapper<RegionDO>();
//				idWrapper.in("id",ids);
//				Map<String, List<RegionDO>> map = regionService.selectList(idWrapper)
//						.stream().collect(Collectors.groupingBy(RegionDO::getParentId));
//				List<String> key = map.keySet().stream().collect(Collectors.toList());
//				List<String> sfIds = splitStrArrayList(user.getRegionProvinceId());  //用户配置的市
//				List<String> notIds = getDiffByHashMap(sfIds, key);  //取出省份列表不包含的id
//
//				if (notIds.size() == 0){
//					return Result.ok(regionService.selectBatchIds(ids));
//				}
//				Wrapper<RegionDO> wrapper = new EntityWrapper<RegionDO>();
//				wrapper.in("parent_id",notIds);
//				List<RegionDO> chengshi1 = regionService.selectList(wrapper);//取出要查询全部的城市
//				List<RegionDO> chengshi2 = regionService.selectBatchIds(ids);
//
//				//将两个集合合成一个并返回
//				List<RegionDO> cszz =new ArrayList();
//				cszz.addAll(chengshi1);
//				cszz.addAll(chengshi2);
//				if(name !=null && !name.equals("")){
//					cszz = cszz.stream().filter(r -> r.getName().contains(name)).collect(Collectors.toList());
//				}
//				return Result.ok(cszz);
//			}
//		}
//		return Result.ok();
//	}


	/**
	 * @param id
	 * @param moneyDg  对公返费金额
	 * @param remark
	 * @param file
	 * @param moneyDs 对私返费金额
	 * @return
	 */
	@Log("修改返费金额-市场总监权限")
	@ResponseBody
	@PostMapping("/updateRefundMoney")
	public Result<?> updateRefundMoney(Long id,Double moneyDg,String remark,String file,Double moneyDs){

		Integer is = userRoleService.userRolenum(this.getUserId());

		if (is!=12){ //不为市场总监权限true
			return Result.fail("权限不足！");
		}

		//查询出考试单
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);

		//修改记录表
		RefundMoneyLogDO refundMoneyLogDO =new RefundMoneyLogDO();
		refundMoneyLogDO.setDgUpdateMoneyBefore(String.valueOf(examinationCostDO.getReturnMoneySchool())); //对公修改前金额
		refundMoneyLogDO.setDgUpdateMoneyLater(String.valueOf(moneyDg)); //对公修改后金额
		refundMoneyLogDO.setDsUpdateMoneyBefore(String.valueOf(examinationCostDO.getReturnMoneyPersonal())); //对私修改前金额
		refundMoneyLogDO.setDsUpdateMoneyLater(String.valueOf(moneyDs)); //对私修改后金额
		refundMoneyLogDO.setRemark(remark); //备注
		refundMoneyLogDO.setFile(file); //文件凭证
		refundMoneyLogDO.setExaminationCostId(id); //考试费id
		refundMoneyLogDO.setCreateDate(new Date()); //创建时间


		examinationCostDO.setUpdateExamine(0); //待审核
		examinationCostDO.setReturnMoney(moneyDg + moneyDs); //总金额 == 对公加对私
		examinationCostDO.setReturnMoneySchool(moneyDg);
		examinationCostDO.setReturnMoneyPersonal(moneyDs);

		examinationCostService.updateById(examinationCostDO);
		refundMoneyLogService.insert(refundMoneyLogDO);
		return Result.ok();
	}





	@Log("修改返费金额-财务审核权限")
	@ResponseBody
	@PostMapping("/updateExamine")
	public Result<?> updateExamine(Long id,int status){

		Integer is = userRoleService.userRolenum(this.getUserId());

		if (is!=10){ //不为财务权限true
			return Result.fail("权限不足！");
		}
		//查询出考试单
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);

		if (examinationCostDO.getUpdateExamine() == null){
			return Result.fail("该数据无需审核！");
		}

		examinationCostDO.setUpdateExamine(status);
		examinationCostService.updateById(examinationCostDO);
		return Result.ok();
	}





	@Log("查询考试单金额修改记录")
	@ResponseBody
	@GetMapping("/selRefundMoneyLog")
	public Result<?> selRefundMoneyLog(Long id){
		EntityWrapper entityWrapper =new EntityWrapper();
		entityWrapper.eq("examination_cost_id",id);
		List list = refundMoneyLogService.selectList(entityWrapper);
		return Result.ok(list);
	}




	/**
	 *
	 * @param type 0 = 查询省 1 = 查询市
	 * @return
	 */
	@ResponseBody
	@GetMapping("/userProvinceSel")
	public Result<?> userProvinceSel(String type){
		UserDO user = getUser();

		List<String> ids =new ArrayList<>();
		if (type.equals("0")) { //省
			ids	= splitStrArrayList(user.getRegionProvinceId());
			if ((user.getRegionProvinceId() == null||"".equals(user.getRegionProvinceId())) && (user.getRegionCityId() == null||"".equals(user.getRegionCityId()))){  //如果没配置任何权限就查询全部省
				Wrapper<RegionDO> wrapper = new EntityWrapper<RegionDO>();
				wrapper.eq("parent_id","0");
				return Result.ok(regionService.selectList(wrapper));
			}else {
				return Result.ok(regionService.selectBatchIds(ids)); //最终结果
			}
		}else if (type.equals("1")){ //城市
			if ((user.getRegionProvinceId() == null||"".equals(user.getRegionProvinceId())) && (user.getRegionCityId() == null||"".equals(user.getRegionCityId()))){  //如果没配置任何权限就查询全部城市
				Wrapper<RegionDO> wrapper = new EntityWrapper<RegionDO>();
				wrapper.ne("parent_id","0");
				return Result.ok(regionService.selectList(wrapper));
			}else {
				ids = splitStrArrayList(user.getRegionCityId()); //获取城市id
				Wrapper<RegionDO> idWrapper = new EntityWrapper<RegionDO>();
				idWrapper.in("id",ids);
				Map<String, List<RegionDO>> map = regionService.selectList(idWrapper)
						.stream().collect(Collectors.groupingBy(RegionDO::getParentId));
				List<String> key = map.keySet().stream().collect(Collectors.toList());
				List<String> sfIds = splitStrArrayList(user.getRegionProvinceId());  //用户配置的市
				List<String> notIds = getDiffByHashMap(sfIds, key);  //取出省份列表不包含的id

				if (notIds.size() == 0){
					return Result.ok(regionService.selectBatchIds(ids));
				}
				Wrapper<RegionDO> wrapper = new EntityWrapper<RegionDO>();
				wrapper.in("parent_id",notIds);
				List<RegionDO> chengshi1 = regionService.selectList(wrapper);//取出要查询全部的城市
				List<RegionDO> chengshi2 = regionService.selectBatchIds(ids);

				//将两个集合合成一个并返回
				List cszz =new ArrayList();
				cszz.addAll(chengshi1);
				cszz.addAll(chengshi2);
				return Result.ok(cszz);
			}
		}
		return Result.ok();
	}




//	/**
//	 *
//	 * @param type 0 = 查询省 1 = 查询市
//	 * @return
//	 */
//	@ResponseBody
//	@GetMapping("/userProvinceSel")
//	public Result<?> userProvinceSel(String type,String name){
//
//		UserDO user = getUser();
//
//		List<String> ids =new ArrayList<>();
//		if (type.equals("0")) { //省
//			ids	= splitStrArrayList(user.getRegionProvinceId());
//			if ((user.getRegionProvinceId() == null||"".equals(user.getRegionProvinceId())) && (user.getRegionCityId() == null||"".equals(user.getRegionCityId()))){  //如果没配置任何权限就查询全部省
//				Wrapper<RegionDO> wrapper = new EntityWrapper<RegionDO>();
//				wrapper.eq("parent_id","0");
//				if (name!=null){
//					wrapper.like("name",name);
//				}
//				return Result.ok(regionService.selectList(wrapper));
//			}else {
//				Wrapper<RegionDO> wrapper = new EntityWrapper<RegionDO>();
//				wrapper.in("id",ids);
//				if (name!=null){
//					wrapper.like("name",name);
//				}
//				return Result.ok(regionService.selectList(wrapper)); //最终结果
//			}
//		}else if (type.equals("1")){ //城市
//			if ((user.getRegionProvinceId() == null||"".equals(user.getRegionProvinceId())) && (user.getRegionCityId() == null||"".equals(user.getRegionCityId()))){  //如果没配置任何权限就查询全部城市
//				Wrapper<RegionDO> wrapper = new EntityWrapper<RegionDO>();
//				wrapper.ne("parent_id","0");
//				if (name!=null){
//					wrapper.like("name",name);
//				}
//				return Result.ok(regionService.selectList(wrapper));
//			}else {
//				ids = splitStrArrayList(user.getRegionCityId()); //获取城市id
//				Wrapper<RegionDO> idWrapper = new EntityWrapper<RegionDO>();
//				idWrapper.in("id",ids);
//				Map<String, List<RegionDO>> map = regionService.selectList(idWrapper)
//						.stream().collect(Collectors.groupingBy(RegionDO::getParentId));
//				List<String> key = map.keySet().stream().collect(Collectors.toList());
//				List<String> sfIds = splitStrArrayList(user.getRegionProvinceId());  //用户配置的市
//				List<String> notIds = getDiffByHashMap(sfIds, key);  //取出省份列表不包含的id
//
//				if (notIds.size() == 0){
//					return Result.ok(regionService.selectBatchIds(ids));
//				}
//				Wrapper<RegionDO> wrapper = new EntityWrapper<RegionDO>();
//				wrapper.in("parent_id",notIds);
//				List<RegionDO> chengshi1 = regionService.selectList(wrapper);//取出要查询全部的城市
//				List<RegionDO> chengshi2 = regionService.selectBatchIds(ids);
//
//				//将两个集合合成一个并返回
//				List<RegionDO> cszz =new ArrayList();
//				cszz.addAll(chengshi1);
//				cszz.addAll(chengshi2);
//
//				if (name!=null){
//					List<RegionDO> regionDOList = cszz.stream().filter(s->s.getName().equals(name)).collect(Collectors.toList());
//					return Result.ok(regionDOList);
//				}
//
//				return Result.ok(cszz);
//			}
//		}
//		return Result.ok();
//	}


	private static String bs = ",";


	private static List<String> splitStrArrayList(String str) {
		List<String> stringList = new ArrayList<>();
		if (str != null) {
			String[] strs = str.split(bs);
			stringList.addAll(Arrays.asList(strs));
			return stringList;
		}
		return null;
	}



	/**
	 * 找出两个list的不同元素,使用hashMap高效特性,数据量越大性能优势体现越为明显
	 * @param list1
	 * @param list2
	 * @return
	 */
	public static List<String> getDiffByHashMap(List<String> list1,List<String> list2){
		long start = System.currentTimeMillis();
		List<String> resultList = new ArrayList<String>();
		//为了防止map扩容增加性能代价；初始化长度为两个链表的长度
		int capacity = (int)((float)(list1.size()+list2.size())/0.75F+1.0F);
		Map<String,Integer> map = new HashMap<>(capacity);
		for (String s:list1) {
			map.put(s,1);
		}
		for (String s:list2) {
			if(map.get(s) == null){
				map.put(s,1);
			}else {
				map.put(s,map.get(s)+1);
			}
		}
		for (Map.Entry m :map.entrySet()) {
			//value 大于1说明元素是两个list共有
			if((int)m.getValue() == 1){
				resultList.add((String)m.getKey());
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("getDiffByHashMap耗时："+(end-start));
		return resultList;
	}





	@ResponseBody
	@GetMapping("/costStandard")
	public Map<String,String> costStandard(String province,String grade){
		Map<String,ProvinceCostStandardBO> map =new HashMap<>();
		ProvinceCostStandardBO provinceCostStandardBO =new ProvinceCostStandardBO();
		//默认标准
		provinceCostStandardBO.setYrzhCostchu("368");//幼儿照护初级收费标准
		provinceCostStandardBO.setYrzhCostzhong("368");//幼儿照护中级收费标准
		provinceCostStandardBO.setYrzhCostgao("368");//幼儿照护高级收费标准
		provinceCostStandardBO.setYrzhreturnCost("80");//幼儿照护初中高返费标准
		provinceCostStandardBO.setChhfCostchu("395");//产后恢复初级收费标准
		provinceCostStandardBO.setChhfCostzhong("395");//产后恢复中级收费标准
		provinceCostStandardBO.setChhfCostgao("395");//产后恢复高级收费标准
		provinceCostStandardBO.setChhfreturnCost("90");//产后恢复初中高返费标准
		map.put(province,provinceCostStandardBO); //省份 + 费用标准
		if ("山东".equals(province)){
			provinceCostStandardBO.setYrzhCostchu("358");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("358");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("358");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("85");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("395");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("395");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("395");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("90");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}
		if ("江苏".equals(province)){
			provinceCostStandardBO.setYrzhCostchu("358");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("358");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("358");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("80");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("395");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("395");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("395");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("90");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}
		if (province.contains("广西")){
			provinceCostStandardBO.setYrzhCostchu("368");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("368");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("368");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("80");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("411");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("411");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("411");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("100");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}
		if ("吉林".equals(province)){
			provinceCostStandardBO.setYrzhCostchu("415");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("415");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("415");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("100");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("395");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("395");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("395");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("90");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}
		if ("黑龙江".equals(province)){
			provinceCostStandardBO.setYrzhCostchu("415");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("415");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("415");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("100");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("395");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("395");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("395");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("95");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}
		if ("宁夏".equals(province)){
			provinceCostStandardBO.setYrzhCostchu("377");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("377");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("377");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("80");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("395");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("395");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("395");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("90");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}
		if ("安徽".equals(province)){
			provinceCostStandardBO.setYrzhCostchu("368");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("368");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("368");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("80");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("395");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("395");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("395");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("95");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}

		if ("重庆".equals(province)){
			provinceCostStandardBO.setYrzhCostchu("400");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("415");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("430");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("100");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("395");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("395");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("395");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("102");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}

		if ("贵州".equals(province)){
			provinceCostStandardBO.setYrzhCostchu("368");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("368");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("368");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("85");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("395");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("395");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("395");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("90");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}

		if ("北京".equals(province)){
			provinceCostStandardBO.setYrzhCostchu("368");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("368");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("368");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("95");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("395");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("395");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("395");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("90");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}
		if ("内蒙".equals(province)){
			provinceCostStandardBO.setYrzhCostchu("315");//幼儿照护初级收费标准
			provinceCostStandardBO.setYrzhCostzhong("315");//幼儿照护中级收费标准
			provinceCostStandardBO.setYrzhCostgao("315");//幼儿照护高级收费标准
			provinceCostStandardBO.setYrzhreturnCost("55");//幼儿照护初中高返费标准
			provinceCostStandardBO.setChhfCostchu("311");//产后恢复初级收费标准
			provinceCostStandardBO.setChhfCostzhong("311");//产后恢复中级收费标准
			provinceCostStandardBO.setChhfCostgao("311");//产后恢复高级收费标准
			provinceCostStandardBO.setChhfreturnCost("51");//产后恢复初中高返费标准
			map.put(province,provinceCostStandardBO); //省份 + 费用标准
		}

		return setProvinceCostStandardBO(province,grade,map);
	}


	//省份价格标准初始化
	private Map<String,String> setProvinceCostStandardBO(String province,String grade,Map<String,ProvinceCostStandardBO> map){
		Map<String,String> rstMap =new HashMap<>();
		ProvinceCostStandardBO provinceCostStandardBO = map.get(province);
		if ("幼儿照护-初级".equals(grade)){
			rstMap.put("costStandard",provinceCostStandardBO.getYrzhCostchu());
			rstMap.put("returnCostStandard",provinceCostStandardBO.getYrzhreturnCost());
		}
		if ("幼儿照护-中级".equals(grade)){
			rstMap.put("costStandard",provinceCostStandardBO.getYrzhCostzhong());
			rstMap.put("returnCostStandard",provinceCostStandardBO.getYrzhreturnCost());
		}
		if ("幼儿照护-高级".equals(grade)){
			rstMap.put("costStandard",provinceCostStandardBO.getYrzhCostgao());
			rstMap.put("returnCostStandard",provinceCostStandardBO.getYrzhreturnCost());
		}
		if ("产后恢复-初级".equals(grade)){
			rstMap.put("costStandard",provinceCostStandardBO.getChhfCostchu());
			rstMap.put("returnCostStandard",provinceCostStandardBO.getChhfreturnCost());
		}
		if ("产后恢复-中级".equals(grade)){
			rstMap.put("costStandard",provinceCostStandardBO.getChhfCostzhong());
			rstMap.put("returnCostStandard",provinceCostStandardBO.getChhfreturnCost());
		}
		if ("产后恢复-高级".equals(grade)){
			rstMap.put("costStandard",provinceCostStandardBO.getChhfCostgao());
			rstMap.put("returnCostStandard",provinceCostStandardBO.getChhfreturnCost());
		}
		return rstMap;
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:examinationCost:examinationCost")
	public Result<Page<ExaminationCostDO>> list(ExaminationCostDO examinationCostDTO,String examStartDate,String examEndDate,int isNormalNum){
		UserDO user = getUser();

		//筛选
		Wrapper<ExaminationCostDO> wrapper = new EntityWrapper<ExaminationCostDO>().orderBy("id", false);
		Wrapper<ExaminationCostDO> wrapperReceivables=new EntityWrapper<ExaminationCostDO>().orderBy("id", false);
		if(!getRoleNames().contains("超级用户角色")&&!getRoleNames().contains("市场总监")&&!getRoleNames().contains("财务审核发票")){
			if(getRoleNames().contains("市场一部管理员")){
				wrapper.eq("region_department","市场一部");
				wrapperReceivables.eq("region_department","市场一部");
			}else if(getRoleNames().contains("市场二部管理员")){
				wrapper.eq("region_department","市场二部");
				wrapperReceivables.eq("region_department","市场二部");
			}else if(getRoleNames().contains("市场三部管理员")){
				wrapper.eq("region_department","市场三部");
				wrapperReceivables.eq("region_department","市场三部");
			}else if(getRoleNames().contains("市场四部管理员")){
				wrapper.eq("region_department","市场四部");
				wrapperReceivables.eq("region_department","市场四部");
			} else {
				wrapper.eq("region_user_id",getUserId());
				wrapperReceivables.eq("region_user_id",getUserId());
			}
		}
		if(examinationCostDTO.getOrgName()!=null) {
			wrapper.like("org_name", examinationCostDTO.getOrgName());
			wrapperReceivables.like("org_name", examinationCostDTO.getOrgName());
		}
		if(examinationCostDTO.getState()!=null) {
			wrapper.eq("state", examinationCostDTO.getState());
			wrapperReceivables.eq("state", examinationCostDTO.getState());
		}
		if(examinationCostDTO.getProvince()!=null) {
			wrapper.like("province", examinationCostDTO.getProvince());
			wrapperReceivables.like("province", examinationCostDTO.getProvince());
		}
		if(examinationCostDTO.getYear()!=null) {
			wrapper.eq("year", examinationCostDTO.getYear());
			wrapperReceivables.eq("year", examinationCostDTO.getYear());
		}
		if(examinationCostDTO.getRegionUserName()!=null){
			wrapper.like("region_user_name",examinationCostDTO.getRegionUserName());
			wrapperReceivables.like("region_user_name",examinationCostDTO.getRegionUserName());
		}

		if(org.apache.commons.lang3.StringUtils.isNotBlank(examStartDate)){
			wrapper.ge("examination_date",examStartDate);
			wrapper.le("examination_date",examEndDate);

			wrapperReceivables.ge("examination_date",examStartDate);
			wrapperReceivables.le("examination_date",examEndDate);
		}
		if(isNormalNum==1){
			wrapper.eq("is_normal",1);
			wrapperReceivables.eq("is_normal",1);
		}
		// 查询列表数据
		Page<ExaminationCostDO> page = examinationCostService.selectPage(getPage(ExaminationCostDO.class),wrapper);
		List list = new ArrayList();


		if(isNormalNum==0){
			wrapper.eq("is_normal",1);
		}

		int isNormal=examinationCostService.selectCount(wrapper);

		wrapperReceivables.eq("state",1);
		int receivablesNum=examinationCostService.selectCount(wrapperReceivables);

		for (int i = 0; i < page.getRecords().size(); i++) {
			ExaminationCostDO obj = (ExaminationCostDO) page.getRecords().get(i);
			if(StringUtil.notEmpty(obj.getReturnSchool())){
				obj.setReturnSchool(obj.getReturnSchool());
			}else {
				obj.setReturnSchool(obj.getOrgName());
			}
			list.add(obj);
		}
		page.setRecords(list);
        return new Result<Page<ExaminationCostDO>>(0,isNormal+","+receivablesNum,page);
	}



	/**
	 * 返费抵考试费抵费学校查询
	 *
	 */
	@RequestMapping("/selectCost2")
	@ResponseBody
	public Result<?> selectCost2(@RequestParam(required = false,defaultValue = "1")int pageNumber, @RequestParam(required = false,defaultValue = "10")int pageSize, String name) {
		// 查询列表数据
		//1 订单发布角色  2 订单审核专员   3 仓库审核专员  4超级用户角色  roleName
		//查询所有用户所属权限
		Integer is = userRoleService.userRolenum(this.getUserId());
		Map map=new HashMap();
		Long chOO1=0l;
		Long chOO2=0l;
		List<RoleDO>  listRole=roleService.findAll();
		List<String> lists=new ArrayList();
		String userID=this.getUserId().toString();
		String year =null;
		if(is==8||is==9||is==18||is==19){
			year ="2022";
			lists.add(userID);
		}if(is==6){
			List lists1=new ArrayList();
			for(RoleDO roleDO:listRole){
				if(roleDO.getRoleName().equals("市场一部")||roleDO.getRoleName().equals("市场一部管理员")){
					chOO1=roleDO.getId();
					lists1.add(chOO1);
					//break;
				}
			}
			EntityWrapper<UserRoleDO> wrapper1 = new EntityWrapper<>();

			wrapper1.in("roleId",lists1);
			//Page<UserRoleDO> page1 =	userRoleService.selectPage(getPages(UserRoleDO.class), wrapper1);
			List <UserRoleDO> userRoleDOS =userRoleService.selectList(wrapper1);
			//List<UserRoleDO> userRoleDOS=	page1.getRecords();
			for(UserRoleDO users:userRoleDOS){
				lists.add(users.getUserId().toString());
			}
			map.put("list1",lists);
		}else if(is==7){
			List lists1=new ArrayList();

			for(RoleDO roleDO:listRole){
				if(roleDO.getRoleName().equals("市场二部")||roleDO.getRoleName().equals("市场二部管理员")){
					chOO1=roleDO.getId();
					lists1.add(chOO1);
					//break;
				}
			}
			EntityWrapper<UserRoleDO> wrapper1 = new EntityWrapper<>();

			wrapper1.in("roleId",lists1);
			List <UserRoleDO> userRoleDOS =userRoleService.selectList(wrapper1);
			for(UserRoleDO users:userRoleDOS){
				lists.add(users.getUserId().toString());
			}
			map.put("list1",lists);
		}else if(is==16){
			List lists1=new ArrayList();

			for(RoleDO roleDO:listRole){
				if(roleDO.getRoleName().equals("市场三部")||roleDO.getRoleName().equals("市场三部管理员")){
					chOO1=roleDO.getId();
					lists1.add(chOO1);
					//break;
				}
			}
			EntityWrapper<UserRoleDO> wrapper1 = new EntityWrapper<>();

			wrapper1.in("roleId",lists1);
			List <UserRoleDO> userRoleDOS =userRoleService.selectList(wrapper1);
			for(UserRoleDO users:userRoleDOS){
				lists.add(users.getUserId().toString());
			}
			map.put("list1",lists);
		}else if(is==7){
			List lists1=new ArrayList();

			for(RoleDO roleDO:listRole){
				if(roleDO.getRoleName().equals("市场四部")||roleDO.getRoleName().equals("市场四部管理员")){
					chOO1=roleDO.getId();
					lists1.add(chOO1);
					//break;
				}
			}
			EntityWrapper<UserRoleDO> wrapper1 = new EntityWrapper<>();

			wrapper1.in("roleId",lists1);
			List <UserRoleDO> userRoleDOS =userRoleService.selectList(wrapper1);
			for(UserRoleDO users:userRoleDOS){
				lists.add(users.getUserId().toString());
			}
			map.put("list1",lists);
		}

		Page<Map<Object,Object>> list1=examinationCostService.selectSchool3(pageNumber,pageSize,name,lists,year);

		return Result.ok(list1);

	}



	@GetMapping("/exportList")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:examinationCost:import")
	public void exportlist( HttpServletRequest request, HttpServletResponse response,ExaminationCostDO examinationCostDTO,String examStartDate,String examEndDate) throws Exception{
		Map map = new HashMap();

		//筛选
		Wrapper<ExaminationCostDO> wrapper = new EntityWrapper<ExaminationCostDO>().orderBy("id", false);
		System.out.println(getRoleNames());
		if(!getRoleNames().contains("超级用户角色")&&!getRoleNames().contains("市场总监")&&!getRoleNames().contains("财务审核发票")){
			if(getRoleNames().contains("市场一部管理员")){
				wrapper.eq("region_department","市场一部");
			}else if(getRoleNames().contains("市场二部管理员")){
				wrapper.eq("region_department","市场二部");
			}else if(getRoleNames().contains("市场三部管理员")){
				wrapper.eq("region_department","市场三部");
			}else if(getRoleNames().contains("市场四部管理员")){
				wrapper.eq("region_department","市场四部");
			}else {
				wrapper.eq("region_user_id",getUserId());
			}
		}
		if(examinationCostDTO.getOrgName()!=null) {
			wrapper.like("org_name", examinationCostDTO.getOrgName());
		}
		if(examinationCostDTO.getState()!=null) {
			wrapper.eq("state", examinationCostDTO.getState());
		}
		if(examinationCostDTO.getProvince()!=null) {
			wrapper.like("province", examinationCostDTO.getProvince());
		}
		if(examinationCostDTO.getYear()!=null) {
			wrapper.eq("year", examinationCostDTO.getYear());
		}
		if(examinationCostDTO.getRegionUserName()!=null){
			wrapper.like("region_user_name",examinationCostDTO.getRegionUserName());
		}

		if(org.apache.commons.lang3.StringUtils.isNotBlank(examStartDate)){
			System.out.println(examStartDate);
			wrapper.ge("examination_date",examStartDate);
			wrapper.le("examination_date",examEndDate);
		}
		List<ExaminationCostDO> examinationCostDOS = examinationCostService.selectList(wrapper);
		if(examinationCostDOS.size()<=0)
			return;
		List<ExaminationCostExportVo> examinationCostExportVoList = new ArrayList<ExaminationCostExportVo>();
		for(ExaminationCostDO c : examinationCostDOS){
			ExaminationCostExportVo exportVo = new ExaminationCostExportVo();
			SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
			exportVo.setExaminationDate(c.getExaminationDate()==null?null:formatter.format(c.getExaminationDate()));
			exportVo.setCommission(c.getCommission()==null?null:c.getCommission().toString());
			exportVo.setLaborWage(c.getLaborWage()==null?null:c.getLaborWage().toString());
			exportVo.setOrgName(c.getOrgName());
			exportVo.setProfile(c.getProfile());
			exportVo.setProvince(c.getProvince());
			exportVo.setReceivables(c.getReceivables()==null?null:c.getReceivables().toString());
			exportVo.setAdvance(c.getAdvance()==null?null:c.getAdvance().toString());
			exportVo.setReceived(c.getReceived()==null?null:c.getReceived().toString());
			exportVo.setPlanStuNum(c.getPlanStuNum()==null?null:c.getPlanStuNum().toString());
			exportVo.setReceivedDate(c.getReceivedDate()==null?null:formatter.format(c.getReceivedDate()));
			exportVo.setReturnMoney(c.getReturnMoney()==null?null:c.getReturnMoney().toString());
			exportVo.setRegionUserName(c.getRegionUserName());
			exportVo.setDepartment(c.getRegionDepartment());
			exportVo.setReturnMoneyPersonal(c.getReturnMoneyPersonal()==null?null:c.getReturnMoneyPersonal().toString());
			exportVo.setReturnMoneySchool(c.getReturnMoneySchool()==null?null:c.getReturnMoneySchool().toString());
			exportVo.setPriceStandard(c.getPriceStandard()==null?null:c.getPriceStandard().toString());
			exportVo.setReturnStandard(c.getReturnStandard()==null?null:c.getReturnStandard().toString());
			exportVo.setCity(c.getCity()==null?null:c.getCity());
			exportVo.setRemark(c.getRemark());
			exportVo.setYear(c.getYear().toString());
			exportVo.setStuNum(c.getStuNum()==null?null:c.getStuNum().toString());
			switch (c.getState()){
				case 0:exportVo.setState("未开始");break;
				case 1:exportVo.setState("已考试");break;
				case 2:exportVo.setState("已收款");break;
				case 3:exportVo.setState("个人已返款");break;
				case 4:exportVo.setState("学校已返款");break;
				case 5:exportVo.setState("已完成");break;
			}
			examinationCostExportVoList.add(exportVo);
		}
		//System.out.println(examinationCostExportVoList.size());
		EasyPoiUtil.exportExcel(examinationCostExportVoList, "考试费用详情表", "考试费用详情表", ExaminationCostExportVo.class,"考试费用详情表", response);

	}

	@GetMapping("/examinationCostAnalysis")
	String examinationCostAnalysis(Model model,ExaminationCostDO examinationCostDTO) throws JSONException {
		if(examinationCostDTO.getYear()!=null)
			model.addAttribute("year",examinationCostDTO.getYear());
		else model.addAttribute("year",0);
	    return "jzweb/examinationCost/examinationCostAnalysis";
	}

	@GetMapping("/getAnalysis")
	@ResponseBody
	@Transactional
	Map getAnalysis(int year) throws JSONException {
		Wrapper<ExaminationCostDO> wrapper = new EntityWrapper<ExaminationCostDO>().orderBy("id", false);
		if(year!=0)
			wrapper.eq("year",year);
		List<ExaminationCostDO> examinationCostDOS = examinationCostService.selectList(wrapper);
		if(examinationCostDOS.size()>0) {
			Map maps = ExaminationCostAnalysisUtil.schoolMap(examinationCostDOS);
			List<Map> statePie = ExaminationCostAnalysisUtil.statePie(examinationCostDOS);
			Map regionAnalysis = ExaminationCostAnalysisUtil.regionAnalysis(examinationCostDOS);
			maps.put("statePie", statePie);
			maps.putAll(regionAnalysis);
			return maps;
		}
		else
			return null;
	}


	@GetMapping("/add")
	@RequiresPermissions("jzweb:examinationCost:add")
	String add(){
		return "jzweb/examinationCost/add";
	}





	/**
	 * 查询所有学校信息
	 * @return
	 */
	@GetMapping("/selectSchool")
	@ResponseBody
	@Log("查询考试批次信息")
	public  Result<?> selectSchool(@RequestParam(required = false,defaultValue = "1")int pageNumber, @RequestParam(required = false,defaultValue = "10")int pageSize, String name){

		Page<Map<Object,Object>> list=bookOrderService.selectSchool(pageNumber,pageSize,name);
		return Result.ok(list);
	}






	@GetMapping("/offset/{id}")
	@RequiresPermissions("jzweb:examinationCost:refundOffset")
	String offset(@PathVariable("id") Long id,Model model){
		ExaminationCostDO examinationCost = examinationCostService.selectById(id);
		if(StringUtil.notEmpty(examinationCost.getReturnSchool())){
			examinationCost.setReturnSchool(examinationCost.getReturnSchool());
		}else {
			examinationCost.setReturnSchool(examinationCost.getOrgName());
		}
		model.addAttribute("examinationCost", examinationCost);
		return "jzweb/examinationCost/offset";
	}





	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:examinationCost:edit")
	String edit(@PathVariable("id") Long id,Model model){
		ExaminationCostDO examinationCost = examinationCostService.selectById(id);
		if(StringUtil.notEmpty(examinationCost.getReturnSchool())){
			examinationCost.setReturnSchool(examinationCost.getReturnSchool());
		}else {
			examinationCost.setReturnSchool(examinationCost.getOrgName());
		}
		model.addAttribute("examinationCost", examinationCost);
	    return "jzweb/examinationCost/edit";
	}


	@GetMapping("/refundMoneyLogEdit/{id}")
//	@RequiresPermissions("jzweb:examinationCost:refundMoneyLogEdit")
	String refundMoneyLogEdit(@PathVariable("id") Long id,Model model){
		ExaminationCostDO examinationCost = examinationCostService.selectById(id);
		model.addAttribute("examinationCost", examinationCost);
 		return "jzweb/examinationCost/refundMoneyLogEdit";
	}


	@GetMapping("/confirmationReturn")
	@RequiresPermissions("jzweb:examinationCost:confirmation")
	String confirmationReturn(Long id,Model model){

		model.addAttribute("id", id);
		return "jzweb/examinationCost/confirmationReturn";
	}

	@Log("提交确认返款")
	@ResponseBody
	@RequestMapping("/confirmationReturnSubmit")
	@RequiresPermissions("jzweb:examinationCost:confirmation")
	public Result<String>  confirmationReturnSubmit( Long id,String objects){
		int r=0;

			ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
			if(examinationCostDO.getState()<2){
				return Result.fail("需先确认收款后才能返款");
			}
			if(examinationCostDO.getState()==5){
				return Result.fail("已全部返款，不可重复操作");
			}
			if(objects.split(";;").length==2){
				examinationCostDO.setState(5);
			}else{
				if(objects.equals("0")){
					if(examinationCostDO.getState()==3)
						examinationCostDO.setState(5);
					else examinationCostDO.setState(4);
				}else{
					if(examinationCostDO.getState()==4)
						examinationCostDO.setState(5);
					else examinationCostDO.setState(3);
				}
			}
			examinationCostService.updateById(examinationCostDO);

		return Result.ok();
	}

	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:examinationCost:add")
	public Result<String> save( ExaminationCostDO examinationCost){
		if ("".equals(examinationCost.getOrgName()) || null == examinationCost.getOrgName()){
			return Result.fail("学校名称不能为空");
		}else  if ("".equals(examinationCost.getProfile()) || null == examinationCost.getProfile()){
			return Result.fail("证书等级不能为空");
		}else  if ("".equals(examinationCost.getProvince()) || null == examinationCost.getProvince()) {
			return Result.fail("省份信息不能为空");
		}else  if ("".equals(examinationCost.getCity()) || null == examinationCost.getCity()){
			return Result.fail("城市信息不能为空");
		}else if ("".equals(examinationCost.getPlanStuNum()) || null == examinationCost.getPlanStuNum()){
			return Result.fail("计划考试人数不能为空");
		}
		examinationCost.setRegionUserId(getUserId());
		examinationCost.setRegionUserName(getUser().getName());
		examinationCost.setRegionDepartment(formatRegionDepartment(getRoleNames()));
		if (examinationCost.getProvince().equals("内蒙")){ //内蒙古的考试费特殊处理全部对私
			examinationCost.setReturnMoneySchoolRatio(0);
			examinationCost.setReturnMoneyPersonalRatio(100);
		}else {
			examinationCost.setReturnMoneySchoolRatio(30);
			examinationCost.setReturnMoneyPersonalRatio(70);
		}
		examinationCost.setState(0);
		examinationCostService.insert(examinationCost);
        return Result.ok();
	}


	//部门名称格式化
	public String formatRegionDepartment(String department){
		//说明只有一个部门
		if(department.length()<=5){
			//对部门名称进行格式化以防拼接逗号
			department = department.substring(0,4);
		}
		return department;
	}



	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:examinationCost:edit")
	public Result<String>  update( ExaminationCostDO examinationCost){
		double sum = examinationCost.getReturnMoneySchoolRatio() + examinationCost.getReturnMoneyPersonalRatio();

		ExaminationCostDO ec = examinationCostService.selectById(examinationCost.getId());
		Integer is = userRoleService.userRolenum(this.getUserId());

		if (!Objects.equals(examinationCost.getPriceStandard(), ec.getPriceStandard())
				|| !Objects.equals(examinationCost.getReturnStandard(), ec.getReturnStandard())) {
			System.out.println("收费标准，返费标准有变更。");

			if (!(is == 12 || is == 4)) {
				return Result.fail("当前角色无权修改费用标准！");
			}
		}

		//拿到计算前的应返款金额
		Double CalculatedBeforeReturnMoney = examinationCost.getReturnMoney();
		Integer hypothecateState = examinationCostService.selectById(examinationCost.getId()).getHypothecateState();
		examinationCost.setHypothecateState(hypothecateState);

		if (sum!=100){
			return Result.fail("占比总和要达到100%！请核查学校返费金额占比与个人返费金额占比！");
		}
		//学校百分之30个人百分之70不为这个数则是修改过了
		if (examinationCost.getReturnMoneySchoolRatio()!=30.0||examinationCost.getReturnMoneyPersonalRatio()!=70.0){
			//不是市场总监
			if (examinationCost.getReturnMoneySchoolRatio()!=0||examinationCost.getReturnMoneyPersonalRatio()!=100){
				if ("10".equals(String.valueOf(is))||"11".equals(String.valueOf(is))||"8".equals(String.valueOf(is))
					||"9".equals(String.valueOf(is))||"1".equals(String.valueOf(is))||"3".equals(String.valueOf(is))||"5".equals(String.valueOf(is))) {
					return Result.fail("当前角色无权修改返费占比！");
				}
			}
		}

		if(examinationCost.getState()<1){
			examinationCost.setStuNum(null);
			boolean update = examinationCostService.updateById(examinationCost);
			return update ? Result.ok() : Result.fail();
		}else{
			if(ec.getStuNum()==null||ec.getStuNum()<=0) {
				return Result.fail("实际考试人数异常！");
			}
			//如果考生数量、返费比率(学校，个人)、收费标准以及返款标准没有变更，则直接update
			if(examinationCost.getReturnMoneyPersonalRatio()==ec.getReturnMoneyPersonalRatio()&&examinationCost.getReturnMoneySchoolRatio()==ec.getReturnMoneySchoolRatio()&&
					examinationCost.getPriceStandard().equals(ec.getPriceStandard())&&examinationCost.getReturnStandard().equals(ec.getReturnStandard())){
				examinationCost.setIsNormal(null);
				if(examinationCost.getPriceStandard() !=null){
					double ys=ec.getStuNum()*examinationCost.getPriceStandard();
					//计算应收款
					examinationCost.setReceivables(ys);
				}
				if (examinationCost.getReturnMoney()!=null && examinationCost.getReturnMoneySchool()!=null && examinationCost.getReturnMoneyPersonal()!=null) {
					//计算应返款
					examinationCost.setReturnMoney(CalculatedBeforeReturnMoney);
					//计算学校应返金额
					examinationCost.setReturnMoneySchool(CalculatedBeforeReturnMoney * (examinationCost.getReturnMoneySchoolRatio() / 100));
					//计算个人应返金额
					examinationCost.setReturnMoneyPersonal(CalculatedBeforeReturnMoney * (examinationCost.getReturnMoneyPersonalRatio() / 100));
				}
				boolean update = examinationCostService.updateById(examinationCost);
				return update ? Result.ok() : Result.fail();
			}else if(examinationCost.getState()>1){
				if(!(getRoleNames().contains("管理员")||getRoleNames().contains("市场总监")||getRoleNames().contains("超级用户")||getRoleNames().contains("财务"))){
					return Result.fail("该数据已收款，修改费用标准请联系市场部管理员！");
				}
			}
			if(examinationCost.getPriceStandard()==null){
				return Result.fail("收费标准不能为空！");
			}
			if(examinationCost.getReturnStandard()==null){
				return Result.fail("返费标准不能为空！");
			}


			double receivables=ec.getStuNum()*examinationCost.getPriceStandard();
			double returnMoney = ec.getStuNum()*examinationCost.getReturnStandard();
			double laborWage = 0.0;
			if(examinationCost.getLaborWage()==null){
				examinationCost.setLaborWage(laborWage);
			}else{
				laborWage=examinationCost.getLaborWage();
			}
			if(ec.getStuNum()!=null||ec.getStuNum()>0){
				examinationCost.setCommission(ec.getStuNum()*3.0);
			}

			//计算应收款
			examinationCost.setReceivables(receivables);

			if (examinationCost.getHypothecateState() != null && examinationCost.getHypothecateState() == 1){
				//计算应返款
				examinationCost.setReturnMoney(CalculatedBeforeReturnMoney);
				//计算学校应返金额
				examinationCost.setReturnMoneySchool(CalculatedBeforeReturnMoney*(examinationCost.getReturnMoneySchoolRatio()/100));
				//计算个人应返金额
				examinationCost.setReturnMoneyPersonal(CalculatedBeforeReturnMoney*(examinationCost.getReturnMoneyPersonalRatio()/100));
			}else {
				//计算应返款
				examinationCost.setReturnMoney(returnMoney);
				//计算学校应返金额
				examinationCost.setReturnMoneySchool(returnMoney*(examinationCost.getReturnMoneySchoolRatio()/100));
				//计算个人应返金额
				examinationCost.setReturnMoneyPersonal(returnMoney*(examinationCost.getReturnMoneyPersonalRatio()/100));
				//计算利润
				examinationCost.setProfit(receivables-returnMoney-laborWage);
				if(examinationCost.getState()>1){
					System.out.println(examinationCost.getReceivables()+"  "+ec.getReceived());
					if(examinationCost.getReceivables().equals(ec.getReceived()))
						examinationCost.setIsNormal(0);
					else examinationCost.setIsNormal(1);
				}
			}
//			if(examinationCost.getPriceStandard() !=null){
//				double ys=ec.getStuNum()*examinationCost.getPriceStandard();
//				//计算应收款
//				examinationCost.setReceivables(ys);
//			}
			boolean update = examinationCostService.updateById(examinationCost);
			return update ? Result.ok() : Result.fail();
		}
	}

	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:remove")
	public Result<String>  remove( Long id){
		//查询角色权限
		Integer is = userRoleService.userRolenum(this.getUserId());

		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);

		//未确认的数据可以进行删除
		if (examinationCostDO.getState() == 0) {
			examinationCostService.deleteById(id);
		}else {
			//如果角色是超级管理员或市场总监
			if ("4".equals(String.valueOf(is))||"1".equals(String.valueOf(is))) {
				examinationCostService.deleteById(id);
			}else {
				return Result.fail("已确认的数据无法进行删除！");
			}
		}
        return Result.ok();
	}

	@Log("预收")
	@PostMapping( "/confirmationAdvance")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:confirmation")
	public Result<String>  confirmationAdvance(Long id,Double advance){
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
		//确认收款
			//如何未输入实收金额，则默认实收金额=应收金额
//			if(advance==null||advance<=0){
//				return Result.fail("请填写预收金额！");
//			}
			examinationCostDO.setAdvanceDate(new Date());
			examinationCostDO.setAdvance(advance);
			examinationCostService.updateById(examinationCostDO);
			return Result.ok();
	}

	@Log("确认收款")
	@PostMapping( "/confirmationReceivable")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:confirmation")
	public Result<String>  confirmationReceivable(Long id,Double received){
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);

//		if(1<examinationCostDO.getState()){
//			return Result.fail("请先确认考试再进行实收");
//		}
		//确认收款
		if (examinationCostDO.getState() == 1||examinationCostDO.getState() == 2) {
			//如果未输入实收金额，则默认实收金额=应收金额
			if(received==-1){
				examinationCostDO.setState(2);
				examinationCostDO.setReceivedDate(new Date());
				examinationCostDO.setReceived(examinationCostDO.getReceivables());
				examinationCostDO.setIsNormal(0);
			}else {
				examinationCostDO.setState(2);
				examinationCostDO.setReceivedDate(new Date());
				examinationCostDO.setReceived(received);
				if(examinationCostDO.getReceivables().equals(examinationCostDO.getReceived()))
					examinationCostDO.setIsNormal(0);
				else examinationCostDO.setIsNormal(1);
			}
			examinationCostService.updateById(examinationCostDO);
			return Result.ok();
		}else{
			return Result.fail("未考试或已返款的数据无法再确认收款");
		}
	}

	@Log("全部回款")
	@PostMapping( "/confirmationReceivableAll")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:confirmationReceivableAll")
	public Result<String>  confirmationReceivableAll(Long id){
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
		//如果未输入实收金额，则默认实收金额=应收金额
		Double received = examinationCostDO.getReceived();//已收款金额
		Double receivables = examinationCostDO.getReceivables();//应收款金额
		// 定义一个允许的误差范围（可根据实际业务需求调整）
		double epsilon = 1e-6; // 默认为1e-6（即0.000001）

        // 使用绝对差值判断两个浮点数是否足够接近（在误差范围内）
		if (abs(received - receivables) > epsilon) {
			return Result.fail("应收与实收金额不一致请核对后操作");
		}
		examinationCostDO.setMoneyAllDate(new Date()); //回款时间
		examinationCostDO.setIsNormal(0);
		examinationCostService.updateById(examinationCostDO);
		return Result.ok();
	}



//	@Log("返费抵款操作")
//	@PostMapping( "/refundOffset")
//	@ResponseBody
//	@Transactional
//	@RequiresPermissions("jzweb:examinationCost:refundOffset")
//	public Result<String> refundOffset(ExaminationCostDO newExaminationCost){
//
//
//
//		if (String.valueOf(newExaminationCost.getId()).equals(newExaminationCost.getExamFeeIf())){
//			return Result.fail("操作失败同一条数据不能进行抵款");
//		}
//
//		//要付款的订单
//		ExaminationCostDO rawExaminationCost =examinationCostService.selectById(newExaminationCost.getId());
//
//
//		//如果下单学校与返费抵抗学校不同则不能抵扣
//		if (rawExaminationCost.getState()<1) {
//			return Result.fail("未确认考试的数据不能进行抵费");
//		}
//		if (newExaminationCost.getExamFeeIf().equals("")){
//			return Result.fail("请选择抵费学校！");
//		}
//
//		if (rawExaminationCost.getReceivables() == rawExaminationCost.getReceived()){
//			return Result.fail("实际收款与应收款相同无需进行抵费");
//		}
//
//
//
//		//返费抵考试费
//		if (org.apache.commons.lang3.StringUtils.isNotBlank(newExaminationCost.getExamFeeIf())) {
//			//要抵扣的订单
//			ExaminationCostDO examinationCostDO = examinationCostService.selectById(newExaminationCost.getExamFeeIf());
//
//
//			if(null != examinationCostDO.getImportReturnState()){
//				if ("1".equals(String.valueOf(examinationCostDO.getImportReturnState()))){
//					return Result.fail("该批次已进行返费操作不能进行抵费");
//				}
//			}
//			//未收款的金额不能进行抵扣
//			if (!rawExaminationCost.getOrgName().equals(examinationCostDO.getOrgName())) {
//				return Result.fail("不能进行该操作原因是：学校名称与抵费学校名称不同");
//			}
//			//如果未收款则不能进行返费抵教材费
//			if (null == examinationCostDO.getReceived()) {
//				return Result.fail("未收款的学校不能进行抵教材费");
//			}
//			//如果实收款小于应收款
//			if (examinationCostDO.getReceived() < examinationCostDO.getReceivables()) {
//				return Result.fail("实际收款小于应收款不能进行抵费操作");
//			}
//			if (examinationCostDO.getReturnMoney()==0) {
//				return Result.fail("应返款为0不能进行抵费操作");
//			}
//
//			//应收款
//			Double receivables = rawExaminationCost.getReceivables();
//			//应返款
//			Double returnMoney = examinationCostDO.getReturnMoney();
//
//
//			int flag = returnMoney.compareTo(receivables);
//			Date date = new Date();
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			Double agio; //差价
//
//
//			//等于1和0表示应返款大于或等于考试费，可以进行全额抵费
//			if (flag == 1 || flag == 0) {
//				//计算差价
//				agio = returnMoney - receivables;
//				//考试数据实际收款金额
//				rawExaminationCost.setReceived(receivables);
//				//已收款
//				rawExaminationCost.setState(2);
//				//收款日期
//				rawExaminationCost.setReceivedDate(date);
//				rawExaminationCost.setReturnMoney(rawExaminationCost.getStuNum() * rawExaminationCost.getReturnStandard());
//				rawExaminationCost.setExamFeeIf(newExaminationCost.getExamFeeIf());
//
//				String newReturnMoneySchoolRatioLs = String.format("%.2f",rawExaminationCost.getReturnMoney() * (rawExaminationCost.getReturnMoneySchoolRatio() / 100));
//				String newReturnMoneyPersonalRatioLs = String.format("%.2f", rawExaminationCost.getReturnMoney() * (rawExaminationCost.getReturnMoneyPersonalRatio() / 100));
//				rawExaminationCost.setReturnMoneySchool(Double.valueOf(newReturnMoneySchoolRatioLs));
//				rawExaminationCost.setReturnMoneyPersonal(Double.valueOf(newReturnMoneyPersonalRatioLs));
//
//				//抵费数据
//				examinationCostDO.setReturnMoney(agio);
//				//对公对私应返金额
//				String returnMoneySchoolRatioLs = String.format("%.2f",examinationCostDO.getReturnMoney() * (examinationCostDO.getReturnMoneySchoolRatio() / 100));
//				String returnMoneyPersonalRatioLs = String.format("%.2f", examinationCostDO.getReturnMoney() * (examinationCostDO.getReturnMoneyPersonalRatio() / 100));
//				examinationCostDO.setReturnMoneySchool(Double.valueOf(returnMoneySchoolRatioLs));
//				examinationCostDO.setReturnMoneyPersonal(Double.valueOf(returnMoneyPersonalRatioLs));
//				String msg = formatMsg(examinationCostDO.getRemark()) + "(已抵扣考试费:"+rawExaminationCost.getReceived()+"元/操作日期："+sdf.format(date)+")";
//				examinationCostDO.setRemark(msg);
//				examinationCostDO.setHypothecateState(1);
//			}
//			//等于-1表示订单订单金额小于返款金额
//			if (flag == -1) {
//				agio = receivables - returnMoney;
//				rawExaminationCost.setReceived(returnMoney);
//				rawExaminationCost.setState(2);
//				rawExaminationCost.setReceivedDate(date);
//				rawExaminationCost.setReturnMoney(rawExaminationCost.getStuNum() * rawExaminationCost.getReturnStandard());
//				rawExaminationCost.setExamFeeIf(newExaminationCost.getExamFeeIf());
//
//				//抵费数据
//				examinationCostDO.setReturnMoney(0.00);
//				String returnMoneySchoolRatioLs = String.format("%.2f",examinationCostDO.getReturnMoney() * (examinationCostDO.getReturnMoneySchoolRatio() / 100));
//				String returnMoneyPersonalRatioLs = String.format("%.2f", examinationCostDO.getReturnMoney() * (examinationCostDO.getReturnMoneyPersonalRatio() / 100));
//				examinationCostDO.setReturnMoneySchool(Double.valueOf(returnMoneySchoolRatioLs));
//				examinationCostDO.setReturnMoneyPersonal(Double.valueOf(returnMoneyPersonalRatioLs));
//				String msg = formatMsg(examinationCostDO.getRemark()) + "(已抵扣考试费:"+rawExaminationCost.getReceived()+"元/操作日期："+sdf.format(date)+")";
//				examinationCostDO.setRemark(msg);
//				examinationCostDO.setHypothecateState(1);
//			}
//			//对考试费进行修改
//			examinationCostService.updateById(examinationCostDO);
//		}
//
//		examinationCostService.updateById(rawExaminationCost);
//		return Result.ok();
//	}
//










	@Log("返费抵款操作")
	@PostMapping( "/refundOffset")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:examinationCost:refundOffset")
	public Result<String> refundOffset(ExaminationCostDO newExaminationCost){

//		List<String> ids =new ArrayList<>();
//		ids.add("1546335842960211974");
//		ids.add("1546335842960211975");
//		newExaminationCost.setExamFeeIfs(ids);

		//考试费抵教材费多个同时抵扣
		if(newExaminationCost.getExamFeeIf()!=null &&!"".equals(newExaminationCost.getExamFeeIf())){
			String[] split = newExaminationCost.getExamFeeIf().split(",");
			List<String> examfeeis =new ArrayList<>();
			for (int i=0;i<split.length;i++){
				examfeeis.add(split[i]);
			}
			newExaminationCost.setExamFeeIfs(examfeeis);
			newExaminationCost.setExamFeeIf("");
		}


		List<ExaminationCostDO> examinationCostDOS = new ArrayList<>(); //要修改的数据抵费数据可以为一条也可以为多条。

		for (int i=0;i<newExaminationCost.getExamFeeIfs().size();i++){
			if (String.valueOf(newExaminationCost.getId()).equals(newExaminationCost.getExamFeeIfs().get(i))){
				return Result.fail("操作失败同一条数据不能进行抵款");
			}
		}

		//要付款的订单
		ExaminationCostDO rawExaminationCost =examinationCostService.selectById(newExaminationCost.getId());


		//如果下单学校与返费抵抗学校不同则不能抵扣
		if (rawExaminationCost.getState()<1) {
			return Result.fail("未确认考试的数据不能进行抵费");
		}
		if (null == newExaminationCost.getExamFeeIfs()){
			return Result.fail("请选择抵费学校！");
		}

		if (rawExaminationCost.getReceivables() == rawExaminationCost.getReceived()){
			return Result.fail("实际收款与应收款相同无需进行抵费");
		}

		//原本应收款金额
		Double saveReceivables = rawExaminationCost.getReceivables();
		//实际收款金额
		Double sjje =0.0;


		for (int i =0;i<newExaminationCost.getExamFeeIfs().size();i++){

			//抵费数据
			ExaminationCostDO examinationCostDO = examinationCostService.selectById(newExaminationCost.getExamFeeIfs().get(i));
			if(null != examinationCostDO.getImportReturnState()){
				if ("1".equals(String.valueOf(examinationCostDO.getImportReturnState()))){
					return Result.fail("该批次已进行返费操作不能进行抵费");
				}
			}
			//未收款的金额不能进行抵扣
			if (!rawExaminationCost.getOrgName().equals(examinationCostDO.getOrgName())) {
				return Result.fail("不能进行该操作原因是：学校名称与抵费学校名称不同");
			}
			//如果未收款则不能进行返费抵教材费
			if (null == examinationCostDO.getReceived()) {
				return Result.fail("未收款的学校不能进行抵教材费");
			}
			//如果实收款小于应收款
			if (examinationCostDO.getReceived() < examinationCostDO.getReceivables()) {
				return Result.fail("实际收款小于应收款不能进行抵费操作");
			}
			if (examinationCostDO.getReturnMoney()==0) {
				return Result.fail("应返款为0不能进行抵费操作");
			}

			if ("1".equals(newExaminationCost.getExamType())&&examinationCostDO.getReturnMoneySchool()==0) {
				return Result.fail("对公返款为0不能进行抵费操作");
			}
			if ("2".equals(newExaminationCost.getExamType())&&examinationCostDO.getReturnMoneyPersonal()==0) {
				return Result.fail("对私返款为0不能进行抵费操作");
			}



			//临时变量-应收款
			Double receivables = rawExaminationCost.getReceivables();

			//应返款总额
			Double returnMoney = 0.0;
			//如果不选择则拿总金额进行抵费
			if (newExaminationCost.getExamType() == null || "".equals(newExaminationCost.getExamType())){
				returnMoney = examinationCostDO.getReturnMoney();
			}else if ("1".equals(newExaminationCost.getExamType())){ //对公
				returnMoney = examinationCostDO.getReturnMoneySchool();
			}else if ("2".equals(newExaminationCost.getExamType())){ //对私
				returnMoney = examinationCostDO.getReturnMoneyPersonal();
			}


			int flag = returnMoney.compareTo(receivables);
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Double agio; //差价

			if (sjje != null) {
				if (saveReceivables.compareTo(sjje) == 0) { //考试费金额和实际收款金额相等则不用在进行遍历了
					break;
				}
			}

			//等于1和0表示应返款大于或等于考试费，可以进行全额抵费
			if (flag == 1 || flag == 0) {
				//计算差价
				agio = returnMoney - receivables;
				//考试数据实际收款金额
				sjje = sjje + receivables;
				//已经抵扣
				rawExaminationCost.setState(10);
				//收款日期
				rawExaminationCost.setReceivedDate(date);
				rawExaminationCost.setReturnMoney(rawExaminationCost.getStuNum() * rawExaminationCost.getReturnStandard());
				String msg = "";
				if (newExaminationCost.getExamType() == null || "".equals(newExaminationCost.getExamType())) { //全额抵
					String returnMoneySchoolRatioLs = String.format("%.2f",examinationCostDO.getReturnMoney() * (examinationCostDO.getReturnMoneySchoolRatio() / 100));
					String returnMoneyPersonalRatioLs = String.format("%.2f", examinationCostDO.getReturnMoney() * (examinationCostDO.getReturnMoneyPersonalRatio() / 100));
					examinationCostDO.setReturnMoneySchool(Double.valueOf(returnMoneySchoolRatioLs));
					examinationCostDO.setReturnMoneyPersonal(Double.valueOf(returnMoneyPersonalRatioLs));
					msg = formatMsg(examinationCostDO.getRemark()) + "(已抵扣考试费:"+receivables+"元/操作日期："+sdf.format(date)+")";
					examinationCostDO.setReturnMoney(agio); //应返款
				}else if ("1".equals(newExaminationCost.getExamType())) { //对公
					examinationCostDO.setReturnMoneySchool(agio);
					msg = formatMsg(examinationCostDO.getRemark()) + "(对公已抵扣考试费:"+receivables+"元/操作日期："+sdf.format(date)+")";
					examinationCostDO.setReturnMoney(examinationCostDO.getReturnMoneySchool() + examinationCostDO.getReturnMoneyPersonal());//应返款金额
				}else if ("2".equals(newExaminationCost.getExamType())){ //对私
					examinationCostDO.setReturnMoneyPersonal(agio);
					msg = formatMsg(examinationCostDO.getRemark()) + "(对私已抵扣教材费:" + receivables + "元/操作日期：" + sdf.format(date) + ")";
					examinationCostDO.setReturnMoney(examinationCostDO.getReturnMoneySchool() + examinationCostDO.getReturnMoneyPersonal());//应返款金额
				}
				examinationCostDO.setRemark(msg);
				examinationCostDO.setHypothecateState(1);
				examinationCostDOS.add(examinationCostDO);

			}
			if (flag == -1) { //不足以全部抵款
				agio = receivables - returnMoney;
				rawExaminationCost.setReceivables(agio);//收款金额
				sjje = sjje + returnMoney;
				rawExaminationCost.setState(10);
				rawExaminationCost.setReceivedDate(date);
				rawExaminationCost.setReturnMoney(rawExaminationCost.getStuNum() * rawExaminationCost.getReturnStandard());

				//抵费数据

				String msg="";
				if (newExaminationCost.getExamType() == null || "".equals(newExaminationCost.getExamType())){
					String returnMoneySchoolRatioLs = String.format("%.2f",examinationCostDO.getReturnMoney() * (examinationCostDO.getReturnMoneySchoolRatio() / 100));
					String returnMoneyPersonalRatioLs = String.format("%.2f", examinationCostDO.getReturnMoney() * (examinationCostDO.getReturnMoneyPersonalRatio() / 100));
					examinationCostDO.setReturnMoneySchool(Double.valueOf(returnMoneySchoolRatioLs));
					examinationCostDO.setReturnMoneyPersonal(Double.valueOf(returnMoneyPersonalRatioLs));
					msg = formatMsg(examinationCostDO.getRemark()) + "(已抵扣考试费:"+returnMoney+"元/操作日期："+sdf.format(date)+")";
					examinationCostDO.setReturnMoney(0.00);
				}else if ("1".equals(newExaminationCost.getExamType())){ //对公
					examinationCostDO.setReturnMoneySchool(0.0);
					msg = formatMsg(examinationCostDO.getRemark()) + "(对公部分已抵扣教材费:" + returnMoney + "元/操作日期：" + sdf.format(date) + ")";
					examinationCostDO.setReturnMoney(examinationCostDO.getReturnMoneyPersonal());
				}else if ("2".equals(newExaminationCost.getExamType())){ //对私
					examinationCostDO.setReturnMoneyPersonal(0.0);
					msg = formatMsg(examinationCostDO.getRemark()) + "(对私部分已抵扣教材费:" + returnMoney + "元/操作日期：" + sdf.format(date) + ")";
					examinationCostDO.setReturnMoney(examinationCostDO.getReturnMoneySchool());
				}
				examinationCostDO.setRemark(msg);
				examinationCostDO.setHypothecateState(1);
				examinationCostDOS.add(examinationCostDO);
			}

		}

		examinationCostService.updateBatchById(examinationCostDOS);

		rawExaminationCost.setReceived(sjje + rawExaminationCost.getReceived()); //实际收款金额
		rawExaminationCost.setReceivables(saveReceivables); //原应返款金额
		String returnMoneySchoolRatioLs = String.format("%.2f",rawExaminationCost.getReturnMoney() * (rawExaminationCost.getReturnMoneySchoolRatio() / 100));
		String returnMoneyPersonalRatioLs = String.format("%.2f", rawExaminationCost.getReturnMoney() * (rawExaminationCost.getReturnMoneyPersonalRatio() / 100));
		rawExaminationCost.setReturnMoneySchool(Double.valueOf(returnMoneySchoolRatioLs));
		rawExaminationCost.setReturnMoneyPersonal(Double.valueOf(returnMoneyPersonalRatioLs));

		if (newExaminationCost.getExamFeeIfs() !=null) {
			if (newExaminationCost.getExamFeeIfs().size() > 0) {
				String examFeeIF = "";
				for (int i = 0; i < newExaminationCost.getExamFeeIfs().size(); i++) {
					examFeeIF = examFeeIF + "," + newExaminationCost.getExamFeeIfs().get(i);
				}
				rawExaminationCost.setExamFeeIf(examFeeIF);
			}
		}

		examinationCostService.updateById(rawExaminationCost);
		return Result.ok();
	}




	private String formatMsg(String msg){
		if (msg==null){
			return "";
		}
		return msg;
	}






	/**
	 * 考试费抵费补款
	 * @param id
	 * @return
	 */
	@GetMapping("/compensation")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:compensation")
	public Result<BookOrderDO> compensation(Long id,String cost){
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
		if (examinationCostDO.getReceived() == null){
			return Result.fail("该订单无法进行补费操作");
		}
		int flag = examinationCostDO.getReceived().compareTo(examinationCostDO.getReceivables());
		if (flag==1 || flag==0){
			return Result.fail("该订单无需进行补款操作");
		}

		if (examinationCostDO.getExamFeeIf() == null || examinationCostDO.getExamFeeIf().equals("")){
			return Result.fail("请先进行抵费操作再进行补款");
		}
		Double cos=Double.valueOf(cost);
		examinationCostDO.setReceived(examinationCostDO.getReceived() + cos);
		examinationCostDO.setState(11);
		examinationCostService.updateById(examinationCostDO);
		return Result.ok();
	}


	@Log("批量确认收款")
	@PostMapping( "/confirmationReceivables")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:confirmation")
	public Result<String>  confirmationReceivables(@RequestParam("ids[]") Long[] ids){
		//批量确认收款，则默认实收金额=应收金额
		int r=0;
		for(Long id : ids) {
			ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
			//确认收款
			if (examinationCostDO.getState() == 1||examinationCostDO.getState() == 2) {
				r++;
				examinationCostDO.setState(2);
				examinationCostDO.setReceivedDate(new Date());
				examinationCostDO.setReceived(examinationCostDO.getReceivables());
				if(examinationCostDO.getReceivables().equals(examinationCostDO.getReceived()))
					examinationCostDO.setIsNormal(0);
				else examinationCostDO.setIsNormal(1);
			}
			examinationCostService.updateById(examinationCostDO);
		}
		if(r==ids.length)
			return Result.ok();
		else{
			return Result.fail("部分确认收款失败，可能已确认收款或未考试");
		}
	}

	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		examinationCostService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

	@Log("修改考试人数")
	@PostMapping( "/editStuNum")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:editStuNum")
	public Result<String>  editStuNum(Long id,Integer stuNum){
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
		if(examinationCostDO.getState()<1){
			return Result.fail("无法修改未确认考试的数据！");
		}
		examinationCostDO.setStuNum(stuNum);
		double receivables=stuNum*examinationCostDO.getPriceStandard();
		double returnMoney = stuNum*examinationCostDO.getReturnStandard();
		double laborWage = 0.0;
		if(examinationCostDO.getLaborWage()==null){
			examinationCostDO.setLaborWage(laborWage);
		}else{
			laborWage=examinationCostDO.getLaborWage();
		}
		//计算应收款
		examinationCostDO.setReceivables(receivables);
		//计算应返款
		examinationCostDO.setReturnMoney(returnMoney);
		//计算学校应返金额
		examinationCostDO.setReturnMoneySchool(returnMoney*0.3);
		//计算个人应返金额
		examinationCostDO.setReturnMoneyPersonal(returnMoney*0.7);
		//计算提成
		examinationCostDO.setCommission(stuNum*3.0);
		//计算利润
		examinationCostDO.setProfit(receivables-returnMoney-laborWage);
		//如果预收款大于等于应收款，则直接更改状态为已收款
		if((examinationCostDO.getReceived()==null||examinationCostDO.getReceived().equals(0))&&examinationCostDO.getAdvance()!=null){
			examinationCostDO.setReceived(examinationCostDO.getAdvance());
			examinationCostDO.setState(2);
		}
		if(examinationCostDO.getState()<=1||examinationCostDO.getReceivables().equals(examinationCostDO.getReceived()))
			examinationCostDO.setIsNormal(0);
		else examinationCostDO.setIsNormal(1);
		examinationCostService.updateById(examinationCostDO);
		return Result.ok("操作成功");
	}
	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Log("导出错误信息")
	@GetMapping("/importcalculateError")
	@ResponseBody
	@Transactional
	@ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
	public void importcalculateError(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//if (!StringUtil.notEmpty(token)) {
		//	UserDO user = this.getClientUser(token);
			// 告诉浏览器用什么软件可以打开此文件
			response.setHeader("content-Type", "application/vnd.ms-excel");
			// 下载文件的默认名称
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("确认考试信息错误", "UTF-8") + ".xls");
			//编码
			response.setCharacterEncoding("UTF-8");
			String jsonArray = EhCacheUtil.get("calculate").toString();
			//  String jsonArray = EhCacheUtil.get("trainingBase" + user.getId()).toString();
			JSONArray arrayList = JSONArray.parseArray(jsonArray);
			//转换为目标对象list
			List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
			Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
			workbook.write(response.getOutputStream());


	//}
	}
	@Log("计算费用")
	@PostMapping( "/calculate")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:calculate")
	public ApiResult<?>  calculate(Long id,Integer stuNum,Date start,String batchName,String costBatchId){

		if(!StringUtil.notEmpty(costBatchId)){
			return ApiResult.fail("请选择需要处理的信息！");
		}
		//获取考试批次id集
		String[] strings = costBatchId.split(",");

		List<String> list = Arrays.asList(strings);
		boolean b=true;
		List<ErrorCodeVo> list1 = new ArrayList<>();

		//查询每一批次学生人数、学生理论成绩大于0人数、学生理论成绩大于0占比率
		List<ExaminationsPercentVo> lists = examinationBatchService.selecltPercent(list);
		//查询每一批次学生人数、学生实操成绩大于0人数、学生实操成绩大于0占比率
		List<ExaminationsPercentVo> lists1 = examinationBatchService.selecltPercent1(list);
		StringBuilder sb = new StringBuilder();
		StringBuilder sb1 = new StringBuilder();

		//遍历理论成绩阅卷人数
		int suml = 0;
		for(int i=0;i<lists.size();i++){
			int s = lists.get(i).getSum().intValue();
			suml += s;
		}
		//遍历理论成绩大于0的阅卷人数
		int sum = 0;
		for(int i=0;i<lists.size();i++){
			int s = lists.get(i).getSum1().intValue();
			sum += s;
		}
		//遍历实操成绩阅卷人数
		int sums = 0;
		for(int i=0;i<lists1.size();i++){
			int s = lists1.get(i).getSum().intValue();
			sums += s;
		}
		//遍历实操成绩大于0的阅卷人数
		int sum1 = 0;
		for(int i=0;i<lists1.size();i++){
			int s = lists1.get(i).getSum1().intValue();
			sum1 += s;
		}

		//确认考试失败返回信息
		sb= new StringBuilder();
		ErrorCodeVo errorCodeVo = new ErrorCodeVo();
		if(Double.valueOf(sum)/Double.valueOf(stuNum) < 0.5){
			sb.append("总考试人数为："+stuNum+"，理论考试阅卷人数为："+suml+"，理论成绩大于0的人数为："+sum+"，理论成绩大于0人数占总考试人数的比例需大于50%才能确定考试。");
			errorCodeVo.setErrorCode(sb.toString());
			list1.add(errorCodeVo);
		}

//		sb1= new StringBuilder();
//		ErrorCodeVo errorCodeVoo = new ErrorCodeVo();
//		if(Double.valueOf(sum1)/Double.valueOf(stuNum) < 0.5){
//			sb1.append("总考试人数为："+stuNum+"，实操考试阅卷人数为："+sums+"，实操成绩大于0的人数为："+sum1+"，实操成绩大于0人数占总考试人数的比例需大于50%才能确定考试。");
//			errorCodeVoo.setErrorCode(sb1.toString());
//			list1.add(errorCodeVoo);
//		}



//		//确认考试失败返回信息
//		for(int i=0;i<lists.size();i++){
//			sb= new StringBuilder();
//			ErrorCodeVo errorCodeVo = new ErrorCodeVo();
//			if(lists.get(i).getPercent() < 0.5){
//				b=false;
//				sb.append("总考试人数为："+stuNum+"，考试批次为："+lists.get(i).getName()+"，理论考试阅卷人数为："+lists.get(i).getSum().intValue()+"，理论成绩大于0的人数为："+lists.get(i).getSum1().intValue()+"，阅卷比例需大于50%才能确定考试。");
//				errorCodeVo.setErrorCode(sb.toString());
//				list1.add(errorCodeVo);
//			}
//		}
//		for(int i=0;i<lists1.size();i++){
//			sb1= new StringBuilder();
//			ErrorCodeVo errorCodeVo1 = new ErrorCodeVo();
//			if(lists1.get(i).getPercent() < 0.5){
//				b=false;
//				sb1.append("总考试人数为：" + stuNum + "，考试批次为：" + lists1.get(i).getName() + "，实操考试阅卷人数为：" + lists1.get(i).getSum().intValue() + "，实操成绩大于0的人数为：" + lists1.get(i).getSum1().intValue()+"，阅卷比例需大于50%才能确定考试。");
//				errorCodeVo1.setErrorCode(sb1.toString());
//				list1.add(errorCodeVo1);
//			}
//		}

 		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
		if(examinationCostDO.getState()>1){
			//return ApiResult.fail(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg())
			b=false;
			ErrorCodeVo errorCodeVo1 = new ErrorCodeVo();

			errorCodeVo1.setErrorCode(sb1.toString());
			list1.add(errorCodeVo1);
			///return Result.fail("操作失败，已确认收费后的数据无法再重新计算费用！");
			return ApiResult.fail("操作失败，已确认收费后的数据无法再重新计算费用！");
		}

		if(list1.size()>0){
			for(int i=0;i<list1.size();i++){
				list1.get(i).setSeq(i);
			}
			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			//将list1存到缓存中
			EhCacheUtil.put("calculate", jsonArray);
			return ApiResult.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}
		examinationCostDO.setState(1);
		examinationCostDO.setStuNum(stuNum);
		double receivables=stuNum*examinationCostDO.getPriceStandard();
		double returnMoney = stuNum*examinationCostDO.getReturnStandard();
		double laborWage = 0.0;
		if(examinationCostDO.getLaborWage()==null){
			examinationCostDO.setLaborWage(laborWage);
		}else{
			laborWage=examinationCostDO.getLaborWage();
		}

//		if (StringUtil.notEmpty(batchName)){ //如果批次包含在线，则全部对私返费
//			String is = isOnline(batchName);
//			if (is.equals("1")){
//				examinationCostDO.setReturnMoneySchoolRatio(0);
//				examinationCostDO.setReturnMoneyPersonalRatio(100);
//			}
//		}
		examinationCostDO.setExaminationBatchId(costBatchId); //批次id多个批次用，隔开

		examinationCostDO.setExaminationDate(start);
		//计算应收款
		examinationCostDO.setReceivables(receivables);
		//计算应返款
		examinationCostDO.setReturnMoney(returnMoney);
		//计算学校应返金额
		examinationCostDO.setReturnMoneySchool(returnMoney*(examinationCostDO.getReturnMoneySchoolRatio()*0.01));
		//计算个人应返金额
		examinationCostDO.setReturnMoneyPersonal(returnMoney*(examinationCostDO.getReturnMoneyPersonalRatio()*0.01));
		//计算提成
		examinationCostDO.setCommission(stuNum*3.0);
		//计算利润
		examinationCostDO.setProfit(receivables-returnMoney-laborWage);
		//如果预收款大于等于应收款，则直接更改状态为已收款
		if((examinationCostDO.getReceived()==null||examinationCostDO.getReceived().equals(0))&&examinationCostDO.getAdvance()!=null){
			examinationCostDO.setReceived(examinationCostDO.getAdvance());
			examinationCostDO.setAdvance(0.0);
			examinationCostDO.setReceivedDate(new Date());
			examinationCostDO.setState(2);
		}
		if(examinationCostDO.getState()<=1||examinationCostDO.getReceivables().equals(examinationCostDO.getReceived()))
			examinationCostDO.setIsNormal(0);
		else examinationCostDO.setIsNormal(1);

		if (StringUtil.notEmpty(batchName)){ //如果batch不为空
			String is = noImport(batchName);
			examinationCostDO.setIsEnelexamen(is);
		}

		examinationCostService.updateById(examinationCostDO);
		return ApiResult.success("确认考试成功！");
		//return Result.ok("操作成功");
	}



	private String noImport(String batchName){
		if(batchName.contains("免") || batchName.contains("补")){
			return "1";
		}
		return "0";
	}

//	private String isOnline(String batchName){
//		if(batchName.contains("线上")){
//			return "1";
//		}
//		return "0";
//	}


	@Log("确认考试批次及人数")
	@PostMapping( "/selBatchStuNum")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:calculate")
	public Result<List<ExaminationBatchDO>>  selBatchStuNum(Long id){
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);

		Integer is = userRoleService.userRolenum(this.getUserId());
		if(is!=12){ //如果不是市场总监权限
			if(examinationCostDO.getState()==1){
				return Result.fail("操作失败，已确认的数据无法再确认考试！");
			}
		}

		if(examinationCostDO.getState()>1){
				return Result.fail("操作失败，已确认收费后的数据无法再确认考试！");
		}

		Wrapper<ExaminationBatchDO> wrapper = new EntityWrapper<ExaminationBatchDO>().orderBy("start_time",true);
		wrapper.like("name",examinationCostDO.getOrgName());
		if(examinationCostDO.getProfile().contains("初级")&&examinationCostDO.getProfile().contains("中级")){
			wrapper.like("name","初级").or().like("name","中级");
		}else if(examinationCostDO.getProfile().contains("初级")){
			wrapper.like("name","初级");
		}else if(examinationCostDO.getProfile().contains("中级")){
			wrapper.like("name","中级");
		}
		else if(examinationCostDO.getProfile().contains("高级")){
			wrapper.like("name","高级");
		}
		if(examinationCostDO.getProfile().contains("产后恢复")){
			wrapper.like("name","产后恢复");
		}else if (examinationCostDO.getProfile().contains("幼儿照顾")){
			wrapper.like("name","幼儿照顾");
		}




//		Integer is = userRoleService.userRolenum(this.getUserId());
//		if (is!=12){ //不为市场总监权限true
//			if (!examinationCostDO.getStuNum().equals(examinationCostDO.getPlanStuNum())){
//				 return Result.fail("实际考试人数与计划录入人数不符！");
//			}
//		}

//		wrapper.like("name",examinationCostDO.getOrgName());
		wrapper.notLike("name","测试");
		wrapper.notLike("name","师资");
		wrapper.notLike("name","考务技术员");
		wrapper.gt("start_time",examinationCostDO.getYear()+"-01-01");
		wrapper.le("start_time",(examinationCostDO.getYear()+1)+"-01-01");
		List<ExaminationBatchDO> examinationBatchDOList = examinationBatchService.selectList(wrapper);
		if(examinationBatchDOList.size()<=0){
			return Result.fail("未查询到相关考试批次，请核实后再确认考试。");
		}
		for(int i=0;i<examinationBatchDOList.size();i++){
			Wrapper<StuSignUpDO> stuSignUpWrapper = new EntityWrapper<>();
			stuSignUpWrapper.eq("cbatch_id",examinationBatchDOList.get(i).getId());
			stuSignUpWrapper.notLike("name","0");
			stuSignUpWrapper.notLike("name","cs");
			stuSignUpWrapper.notLike("name","测试");
			List<StuSignUpDO> stuSignUpDOS = stuSignUpService.selectList(stuSignUpWrapper);
			examinationBatchDOList.get(i).setStuNum(stuSignUpDOS.size());
		}

		List<ExaminationBatchDO> retList =new ArrayList<>();

		for (int i =0;i<examinationBatchDOList.size();i++){
			Wrapper<ExaminationCostDO> examinationCostDOEntityWrapper = new EntityWrapper<>();
			examinationCostDOEntityWrapper.like("examination_batch_id",examinationBatchDOList.get(i).getId().toString());
			List<ExaminationCostDO> examinationCostDOS = examinationCostService.selectList(examinationCostDOEntityWrapper);
			if (examinationCostDOS.size() == 0){
				retList.add(examinationBatchDOList.get(i));
			}
		}

		if(retList.size()<=0){
			return Result.fail("未查询到相关考试批次，请核实后再确认考试！");
		}
		return Result.ok(retList);
	}



	/**
	 * 考试费数据拷贝
	 *
	 * @throws Exception
	 */
	@Log("考试费数据拷贝")
	@GetMapping("/exCostCopy")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:exCostCopy")
	public Result<Boolean> exCostCopy(Long id) throws Exception {
		ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
		examinationCostDO.setId(null);
		boolean rst = examinationCostService.insert(examinationCostDO);
		return Result.ok(rst);
	}






	@Log("批量核对人数")
	@PostMapping( "/checkStuNum")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationCost:checkStuNum")
	public Result<String>  checkStuNum(@RequestParam("ids[]") Long[] ids){
		String msg = "";
		for(Long id : ids) {
			ExaminationCostDO examinationCostDO = examinationCostService.selectById(id);
			if(examinationCostDO.getState()!=1){
				msg = "部分数据核对失败，只能核对状态为“已计算”的数据";
				continue;
			}
			examinationCostDO.setState(2);
			examinationCostService.updateById(examinationCostDO);
		}
		return Result.ok(msg);
	}

	/**
	 * 下载导入模板
	 *
	 * @param response
	 */
	@RequestMapping("/downloadImportTemplate")
	@RequiresPermissions("jzweb:examinationCost:import")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response) {
		List<ExaminationCostImportVo> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "考试费用详情导入模板", "考试费用详情导入模板", ExaminationCostImportVo.class, "考试费用详情导入模板", response);
	}








//	/**
//	 * 考试费用详情表导入
//	 *
//	 * @param file excel文件,cType:专家类型（0师资，1考评员）
//	 */
//	@Log("考试费用详情表导入")
//	@PostMapping("/import")
//	@ResponseBody
//	@Transactional
//	@RequiresPermissions("jzweb:examinationCost:import")
//	public Result<?> importExcel(@RequestParam("file") MultipartFile file) {
//		//---------------------------------检测导入信息及条件-----------------------------------------
//		//第一步--判断文件格式
//		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
//			return Result.fail("文件格式错误，请选择.xls文件");
//		}
//
//		//第二步--解析文件获得数据
//		List<ExaminationCostImportVo> list = EasyPoiUtil.importExcel(file, 1, 1, ExaminationCostImportVo.class);
//		if (list.size() == 0) {
//			return Result.fail("Excel数据为空，请完善");
//		}
//
//		//---------------------------------验证数据并导入-----------------------------------------
//		//数据该表第三行，第一行标题，第二行表头
//		int startRow = 3;
//		int cout = 1;//错误信息计数
//		List<ExaminationCostDO> examCostList = new ArrayList<>();
//		List<ErrorCodeVo> list1 = new ArrayList<>();
//		List<ExaminationCostImportVo> cerUtilsVos = new ArrayList<>();
//
//		for (int i = 0; i < list.size(); i++) {
//			StringBuilder sb = new StringBuilder();
//			if(StringUtils.isNullOrEmpty(list.get(i).getRegionUserName())){
//				sb.append("第" + (i + startRow) + "行区域负责人姓名未填写，请完善！" + ";");
//			}else if(StringUtils.isNullOrEmpty(list.get(i).getMobile())){
//				sb.append("第" + (i + startRow) + "行区域负责人手机号未填写，请完善！" + ";");
//			}else if(StringUtils.isNullOrEmpty(list.get(i).getOrgName())){
//				sb.append("第" + (i + startRow) + "行学校名称未填写，请完善！" + ";");
//			}else if(StringUtils.isNullOrEmpty(list.get(i).getProvince())){
//				sb.append("第" + (i + startRow) + "行省份未填写，请完善！" + ";");
//			}else if(StringUtils.isNullOrEmpty(list.get(i).getDepartment())){
//				sb.append("第" + (i + startRow) + "行所属部门未填写，请完善！" + ";");
//			}else if(StringUtils.isNullOrEmpty(list.get(i).getProfile())){
//				sb.append("第" + (i + startRow) + "行证书及等级未填写，请完善！" + ";");
//			}else if(StringUtils.isNullOrEmpty(list.get(i).getYear())){
//				sb.append("第" + (i + startRow) + "行年份未填写，请完善！" + ";");
//			}else if(StringUtils.isNullOrEmpty(list.get(i).getPlanStuNum())){
//				sb.append("第" + (i + startRow) + "行计划考试人数未填写，请完善！" + ";");
//			}else if(StringUtils.isNullOrEmpty(list.get(i).getPriceStandard())){
//				sb.append("第" + (i + startRow) + "行收费标准未填写，请完善！" + ";");
//			}else if(StringUtils.isNullOrEmpty(list.get(i).getReturnStandard())){
//				sb.append("第" + (i + startRow) + "行返费标准未填写，请完善！" + ";");
//			}else if(StringUtils.isNullOrEmpty(list.get(i).getState())){
//				sb.append("第" + (i + startRow) + "行状态未填写，请完善！" + ";");
//			}else if(!IdCardUtil.isNumeric(list.get(i).getYear())){
//				sb.append("第" + (i + startRow) + "行年份格式错误，只能填数字！" + ";");
//			}else if(!IdCardUtil.isNumeric(list.get(i).getPlanStuNum())){
//				sb.append("第" + (i + startRow) + "行计划考试人数格式错误，只能填数字！" + ";");
//			}else if(!StringUtils.isNullOrEmpty(list.get(i).getStuNum())&&!IdCardUtil.isNumeric(list.get(i).getStuNum())){
//				sb.append("第" + (i + startRow) + "行实际人数格式错误，只能填数字！" + ";");
//			}else if(!IdCardUtil.isNumericDou(list.get(i).getPriceStandard())){
//				sb.append("第" + (i + startRow) + "行收费标准格式错误，只能填数值！" + ";");
//			}else if(!IdCardUtil.isNumericDou(list.get(i).getReturnStandard())){
//				sb.append("第" + (i + startRow) + "行返费标准格式错误，只能填数值！" + ";");
//			}else{
//				if (!ValidUtils.isMobile(list.get(i).getMobile())) {
//					sb.append("第" + (i + startRow) + "行手机号码格式错误，请修改！" + ";");
//				}else{
//					if(!DepartmentTest(list.get(i).getDepartment())){
//						sb.append("第" + (i + startRow) + "行所属部门填写错误，请修改！" + ";");
//					}else {
//						UserDO user = userService.findOneByKv("mobile", list.get(i).getMobile());
//						//创建用户
//						if (user == null) {
//							user = new UserDO();
//							user.setName(list.get(i).getRegionUserName());
//							user.setUsername(list.get(i).getRegionUserName());
//							String password = "000000";
//							String salt = UUIDUtils.get();
//							String encodePasswd = PasswdUtils.get(password, salt);
//							user.setSalt(salt);
//							user.setPassword(encodePasswd);
//							user.setMobile(list.get(i).getMobile());
//							user.setType(0);//默认个人会员
//							user.setMoney(BigDecimal.valueOf(0.0));//默认0元
//							user.setGmtCreate(new Date());
//							user.setGmtModified(user.getGmtCreate());
//							user.setStatus(1);//默认正常
//							user.setSex(0L);//性别，默认未知
//							userService.insert(user);
//							//配置角色
//							RoleDO roleDO = roleService.findOneByKv("roleName",list.get(i).getDepartment());
//							UserRoleDO userRoleDO = new UserRoleDO();
//							userRoleDO.setRoleId(roleDO.getId());
//							userRoleDO.setUserId(user.getId());
//							userRoleService.insert(userRoleDO);
//						}else{
//							//判断用户表中的姓名与该表中的姓名是否一致，不一致则按照该表修改用户表
//							if(user.getName()==null||!user.getName().equals(list.get(i).getRegionUserName())){
//								user.setName(list.get(i).getRegionUserName());
//								userService.updateById(user);
//							}
//							//判断该用户是否已经配置相关角色
//							RoleDO roleDO = roleService.findOneByKv("roleName",list.get(i).getDepartment());
//							UserRoleDO userRoleDO = userRoleService.findOneByKv("roleId",roleDO.getId(),"userId",user.getId());
//							if(userRoleDO==null){
//								userRoleDO = new UserRoleDO();
//								userRoleDO.setRoleId(roleDO.getId());
//								userRoleDO.setUserId(user.getId());
//								userRoleService.insert(userRoleDO);
//							}
//						}
//
//						//
//						Double priceStandard=Double.parseDouble(list.get(i).getPriceStandard());
//						Double returnStandard = Double.parseDouble(list.get(i).getReturnStandard());
//						ExaminationCostDO examinationCostDO = new ExaminationCostDO();
//						examinationCostDO.setOrgName(list.get(i).getOrgName());
//						examinationCostDO.setReturnMoneySchoolRatio(30);
//						examinationCostDO.setReturnMoneyPersonalRatio(70);
//						examinationCostDO.setYear(Integer.parseInt(list.get(i).getYear()));
//						examinationCostDO.setProvince(list.get(i).getProvince());
//						examinationCostDO.setProfile(list.get(i).getProfile());
//						examinationCostDO.setPlanStuNum(Integer.parseInt(list.get(i).getPlanStuNum()));
//						examinationCostDO.setPriceStandard(priceStandard);
//						examinationCostDO.setReturnStandard(returnStandard);
//						examinationCostDO.setRegionUserId(user.getId());
//						examinationCostDO.setRegionUserName(user.getName());
//						examinationCostDO.setRegionDepartment(list.get(i).getDepartment());
//						if(!StringUtils.isNullOrEmpty(list.get(i).getLaborWage())){
//							examinationCostDO.setLaborWage(Double.parseDouble(list.get(i).getLaborWage()));
//						}
//						if(!StringUtils.isNullOrEmpty(list.get(i).getLaborWage())){
//							examinationCostDO.setLaborWage(Double.parseDouble(list.get(i).getLaborWage()));
//						}
//						if(list.get(i).getExaminationDate()!= null){
//							examinationCostDO.setExaminationDate(list.get(i).getExaminationDate());
//						}
//
//						if(!StringUtils.isNullOrEmpty(list.get(i).getStuNum())){
//							int stuNum=Integer.parseInt(list.get(i).getStuNum());
//							examinationCostDO.setStuNum(stuNum);
//							examinationCostDO.setReceivables(stuNum*priceStandard);
//							examinationCostDO.setReturnMoney(stuNum*returnStandard);
//							examinationCostDO.setReturnMoneyPersonal((stuNum*returnStandard)*0.7);
//							examinationCostDO.setReturnMoneySchool((stuNum*returnStandard)*0.3);
//							examinationCostDO.setCommission(stuNum*3.0);
//						}
//						if(list.get(i).getState().equals("未开始"))
//							examinationCostDO.setState(0);
//						else if(!list.get(i).getState().equals("未开始")&&StringUtils.isNullOrEmpty(list.get(i).getStuNum())){
//							sb.append("第" + (i + startRow) + "行数据已考试，但实际考试人数未填写，请完善！" + ";");
//							continue;
//						}
//						else if(list.get(i).getState().equals("已考试")){
//							examinationCostDO.setState(1);
//						}
//						else if(list.get(i).getState().equals("已回款")){
//							if(StringUtils.isNullOrEmpty(list.get(i).getReceived())){
//								examinationCostDO.setReceived(examinationCostDO.getReceivables());
//							}else{
//								examinationCostDO.setReceived(Double.parseDouble(list.get(i).getReceived()));
//							}
//							examinationCostDO.setState(2);
//						}
//						else if(list.get(i).getState().equals("个人已返款"))
//							examinationCostDO.setState(3);
//						else if(list.get(i).getState().equals("学校已返款"))
//							examinationCostDO.setState(4);
//						else if(list.get(i).getState().equals("已完成"))
//							examinationCostDO.setState(5);
//						else{
//							sb.append("第" + (i + startRow) + "行状态填写错误，请修改！" + ";");
//							continue;
//						}
//						examCostList.add(examinationCostDO);
//					}
//				}
//			}
//
//			if (sb.length() > 0) {
//				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
//				errorCodeVo.setSeq(cout);
//				cout += 1;
//				errorCodeVo.setErrorCode(sb.toString());
//				list1.add(errorCodeVo);
//			}
//		}
//		if (list1.size() == 0) {
//			examinationCostService.insertBatch(examCostList);
//			return Result.ok("成功导入" + list.size() + "条数据");
//		}else{
//			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
//			//将list1存到缓存中
//			EhCacheUtil.put("trainingCertificates" + this.getUserId(), jsonArray);
//			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
//		}
//	}
//






	/**
	 * 考试费用详情表导入 剔重,无需判断区域负责人手机号
	 *
	 * @param file excel文件,cType:专家类型（0师资，1考评员）
	 */
	@Log("考试费用详情表导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:examinationCost:import")
	public Result<?> importExcel(@RequestParam("file") MultipartFile file) {
		//---------------------------------检测导入信息及条件-----------------------------------------
		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		//第二步--解析文件获得数据
		List<ExaminationCostImportVo> list = EasyPoiUtil.importExcel(file, 1, 1, ExaminationCostImportVo.class);
		System.out.println("解析的最后一条数据为："+list.get(list.size()-1).toString());

		list.remove(list.size()-1);

		System.out.println("删除后的最后一条数据为："+list.get(list.size()-1).toString());

		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}

		//剔重后的Excel集合
		List<ExaminationCostImportVo> examinationCostImportVosTc=new ArrayList<>();

		Wrapper<ExaminationCostDO> wrapper = new EntityWrapper<ExaminationCostDO>();
		wrapper.eq("year","2022");

		List<ExaminationCostDO> examinationCostDOAll = examinationCostService.selectList(wrapper);


		for (int i=0;i<list.size();i++){
			int bs=0; //每次循环标识都为0
			for (int j=0;j<examinationCostDOAll.size();j++){
				//如果这条Excel数据等于 数据库中的某条数据就终止本次循环
				System.out.println("第"+i+"次循环-----------------------------------------------");
				boolean a =list.get(i).getProfile().equals(examinationCostDOAll.get(j).getProfile());
				boolean b =list.get(i).getOrgName().equals(examinationCostDOAll.get(j).getOrgName());
				boolean c =list.get(i).getPlanStuNum().equals(examinationCostDOAll.get(j).getPlanStuNum().toString());
				if (list.get(i).getProfile().equals(examinationCostDOAll.get(j).getProfile())&&list.get(i).getOrgName().equals(examinationCostDOAll.get(j).getOrgName())&&list.get(i).getPlanStuNum().equals(examinationCostDOAll.get(j).getPlanStuNum().toString())){
					bs=1; //标识等于1标识数据已经存在了直接结束本次循环
					break;
				}
			}
			if (bs==0) { //标识等于0表示数据不存在可以增加
				examinationCostImportVosTc.add(list.get(i));
			}
		}

		//清除list原有数据
		list =new ArrayList<>();

		for (int i=0;i<examinationCostImportVosTc.size();i++){
			Map<String, String> map = costStandard(examinationCostImportVosTc.get(i).getProvince(), examinationCostImportVosTc.get(i).getProfile());
			examinationCostImportVosTc.get(i).setPriceStandard(map.get("costStandard"));
			examinationCostImportVosTc.get(i).setReturnStandard(map.get("returnCostStandard"));
			examinationCostImportVosTc.get(i).setState("未开始"); //默认都是未开始
			examinationCostImportVosTc.get(i).setStuNum("0");//实际考试人数0

			Wrapper<UserDO> userWrapper = new EntityWrapper<UserDO>();
			userWrapper.eq("name",examinationCostImportVosTc.get(i).getRegionUserName());
			List<UserDO> userDOS = userService.selectList(userWrapper);
			examinationCostImportVosTc.get(i).setMobile(userDOS.get(0).getMobile());
			list.add(examinationCostImportVosTc.get(i));
		}

		//---------------------------------验证数据并导入-----------------------------------------
		//数据该表第三行，第一行标题，第二行表头
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<ExaminationCostDO> examCostList = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		List<ExaminationCostImportVo> cerUtilsVos = new ArrayList<>();

		for (int i = 0; i < list.size(); i++) {
			StringBuilder sb = new StringBuilder();
			if(StringUtils.isNullOrEmpty(list.get(i).getRegionUserName())){
				sb.append("第" + (i + startRow) + "行区域负责人姓名未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getOrgName())){
				sb.append("第" + (i + startRow) + "行学校名称未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getProvince())){
				sb.append("第" + (i + startRow) + "行省份未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getDepartment())){
				sb.append("第" + (i + startRow) + "行所属部门未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getProfile())){
				sb.append("第" + (i + startRow) + "行证书及等级未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getYear())){
				sb.append("第" + (i + startRow) + "行年份未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getPlanStuNum())){
				sb.append("第" + (i + startRow) + "行计划考试人数未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getPriceStandard())){
				sb.append("第" + (i + startRow) + "行收费标准未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getReturnStandard())){
				sb.append("第" + (i + startRow) + "行返费标准未填写，请完善！" + ";");
			}else if(StringUtils.isNullOrEmpty(list.get(i).getState())){
				sb.append("第" + (i + startRow) + "行状态未填写，请完善！" + ";");
			}else if(!IdCardUtil.isNumeric(list.get(i).getYear())){
				sb.append("第" + (i + startRow) + "行年份格式错误，只能填数字！" + ";");
			}else if(!IdCardUtil.isNumeric(list.get(i).getPlanStuNum())){
				sb.append("第" + (i + startRow) + "行计划考试人数格式错误，只能填数字！" + ";");
			}else if(!StringUtils.isNullOrEmpty(list.get(i).getStuNum())&&!IdCardUtil.isNumeric(list.get(i).getStuNum())){
				sb.append("第" + (i + startRow) + "行实际人数格式错误，只能填数字！" + ";");
			}else if(!IdCardUtil.isNumericDou(list.get(i).getPriceStandard())){
				sb.append("第" + (i + startRow) + "行收费标准格式错误，只能填数值！" + ";");
			}else if(!IdCardUtil.isNumericDou(list.get(i).getReturnStandard())){
				sb.append("第" + (i + startRow) + "行返费标准格式错误，只能填数值！" + ";");
			}else{
				if (!ValidUtils.isMobile(list.get(i).getMobile())) {
					sb.append("第" + (i + startRow) + "行手机号码格式错误，请修改！" + ";");
				}else{
					if(!DepartmentTest(list.get(i).getDepartment())){
						sb.append("第" + (i + startRow) + "行所属部门填写错误，请修改！" + ";");
					}else {
						UserDO user = userService.findOneByKv("mobile", list.get(i).getMobile());
						//创建用户
						if (user == null) {
							user = new UserDO();
							user.setName(list.get(i).getRegionUserName());
							user.setUsername(list.get(i).getRegionUserName());
							String password = "000000";
							String salt = UUIDUtils.get();
							String encodePasswd = PasswdUtils.get(password, salt);
							user.setSalt(salt);
							user.setPassword(encodePasswd);
							user.setMobile(list.get(i).getMobile());
							user.setType(0);//默认个人会员
							user.setMoney(BigDecimal.valueOf(0.0));//默认0元
							user.setGmtCreate(new Date());
							user.setGmtModified(user.getGmtCreate());
							user.setStatus(1);//默认正常
							user.setSex(0L);//性别，默认未知
							userService.insert(user);
							//配置角色
							RoleDO roleDO = roleService.findOneByKv("roleName",list.get(i).getDepartment());
							UserRoleDO userRoleDO = new UserRoleDO();
							userRoleDO.setRoleId(roleDO.getId());
							userRoleDO.setUserId(user.getId());
							userRoleService.insert(userRoleDO);
						}else{
							//判断用户表中的姓名与该表中的姓名是否一致，不一致则按照该表修改用户表
							if(user.getName()==null||!user.getName().equals(list.get(i).getRegionUserName())){
								user.setName(list.get(i).getRegionUserName());
								userService.updateById(user);
							}
							//判断该用户是否已经配置相关角色
							RoleDO roleDO = roleService.findOneByKv("roleName",list.get(i).getDepartment());
							UserRoleDO userRoleDO = userRoleService.findOneByKv("roleId",roleDO.getId(),"userId",user.getId());
							if(userRoleDO==null){
								userRoleDO = new UserRoleDO();
								userRoleDO.setRoleId(roleDO.getId());
								userRoleDO.setUserId(user.getId());
								userRoleService.insert(userRoleDO);
							}
						}

						//
						Double priceStandard=Double.parseDouble(list.get(i).getPriceStandard());
						Double returnStandard = Double.parseDouble(list.get(i).getReturnStandard());
						ExaminationCostDO examinationCostDO = new ExaminationCostDO();
						examinationCostDO.setOrgName(list.get(i).getOrgName());
						examinationCostDO.setReturnMoneySchoolRatio(30);
						examinationCostDO.setReturnMoneyPersonalRatio(70);
						examinationCostDO.setYear(Integer.parseInt(list.get(i).getYear()));
						examinationCostDO.setProvince(list.get(i).getProvince());
						examinationCostDO.setProfile(list.get(i).getProfile());
						examinationCostDO.setPlanStuNum(Integer.parseInt(list.get(i).getPlanStuNum()));
						examinationCostDO.setPriceStandard(priceStandard);
						examinationCostDO.setReturnStandard(returnStandard);
						examinationCostDO.setRegionUserId(user.getId());
						examinationCostDO.setRegionUserName(user.getName());
						examinationCostDO.setRegionDepartment(list.get(i).getDepartment());
						if(!StringUtils.isNullOrEmpty(list.get(i).getLaborWage())){
							examinationCostDO.setLaborWage(Double.parseDouble(list.get(i).getLaborWage()));
						}
						if(!StringUtils.isNullOrEmpty(list.get(i).getLaborWage())){
							examinationCostDO.setLaborWage(Double.parseDouble(list.get(i).getLaborWage()));
						}
						if(list.get(i).getExaminationDate()!= null){
							examinationCostDO.setExaminationDate(list.get(i).getExaminationDate());
						}

						if(!StringUtils.isNullOrEmpty(list.get(i).getStuNum())){
							int stuNum=Integer.parseInt(list.get(i).getStuNum());
							examinationCostDO.setStuNum(stuNum);
							examinationCostDO.setReceivables(stuNum*priceStandard);
							examinationCostDO.setReturnMoney(stuNum*returnStandard);
							examinationCostDO.setReturnMoneyPersonal((stuNum*returnStandard)*0.7);
							examinationCostDO.setReturnMoneySchool((stuNum*returnStandard)*0.3);
							examinationCostDO.setCommission(stuNum*3.0);
						}
						if(list.get(i).getState().equals("未开始"))
							examinationCostDO.setState(0);
						else if(!list.get(i).getState().equals("未开始")&&StringUtils.isNullOrEmpty(list.get(i).getStuNum())){
							sb.append("第" + (i + startRow) + "行数据已考试，但实际考试人数未填写，请完善！" + ";");
							continue;
						}
						else if(list.get(i).getState().equals("已考试")){
							examinationCostDO.setState(1);
						}
						else if(list.get(i).getState().equals("已回款")){
							if(StringUtils.isNullOrEmpty(list.get(i).getReceived())){
								examinationCostDO.setReceived(examinationCostDO.getReceivables());
							}else{
								examinationCostDO.setReceived(Double.parseDouble(list.get(i).getReceived()));
							}
							examinationCostDO.setState(2);
						}
						else if(list.get(i).getState().equals("个人已返款"))
							examinationCostDO.setState(3);
						else if(list.get(i).getState().equals("学校已返款"))
							examinationCostDO.setState(4);
						else if(list.get(i).getState().equals("已完成"))
							examinationCostDO.setState(5);
						else{
							sb.append("第" + (i + startRow) + "行状态填写错误，请修改！" + ";");
							continue;
						}
						examCostList.add(examinationCostDO);
					}
				}
			}

			if (sb.length() > 0) {
				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
				errorCodeVo.setSeq(cout);
				cout += 1;
				errorCodeVo.setErrorCode(sb.toString());
				list1.add(errorCodeVo);
			}
		}
		if (list1.size() == 0) {
			examinationCostService.insertBatch(examCostList);
			return Result.ok("成功导入" + list.size() + "条数据");
		}else{
			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			//将list1存到缓存中
			EhCacheUtil.put("trainingCertificates" + this.getUserId(), jsonArray);
			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}
	}
















	private boolean DepartmentTest(String department){
		if(department.equals("市场一部")||department.equals("市场二部")||department.equals("市场三部")||department.equals("市场四部")||department.equals("市场一部管理员")||department.equals("市场二部管理员")||department.equals("市场三部管理员")||department.equals("市场四部管理员"))
			return true;
		return false;
	}

	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importError")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:examinationCost:import")
	public void importError(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考试费用详情导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("trainingCertificates" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}


}
